我开始使用 Ruby on Rails,但遇到了一些困难。
为了提供一些背景信息,我想做的是一款用户可以创建帐户的应用程序,每个帐户都有一个 channel ,每个 channel 都有一定数量的视频。
还有一个时间线,每个视频都可以向其中添加视频。所以时间线也有很多视频。
现在我有以下模型:
class Channel < ActiveRecord::Base
belongs_to :member
has_many :videos
end
class Member < ActiveRecord::Base
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
has_one :channel
has_many :timelines
end
class Video < ActiveRecord::Base
belongs_to :channel
end
class Timeline < ActiveRecord::Base
belongs_to :member
has_many :videos
end
如何建立视频既属于 channel 又属于时间线的关系?
我认为最好的方法是创建一个名为 timelinerelation 的新表,其中包含字段 ID_TIMELINE、ID_VIDEO 等对于时间线 1,我有视频 2,3,4,对于时间线 2,我有视频 3,4,5。
所以 table 上会有:
1 2;
1 3;
1 4;
2 3;
2 4;
2 5;
问题是,我不知道如何在 ruby on Rails 中执行此操作。
最佳答案
根据您提供的示例,我发现一个视频可以属于多个时间线。如果是这样,您需要设置多对多关系,如概述here .
在您的情况下,您可以通过运行创建一个连接模型,例如 TimelineRelation
:
rails g model TimelineRelation 时间线:引用视频:引用
class Video < ActiveRecord::Base
belongs_to :channel
has_many :timeline_relations
has_many :timelines, through: timeline_relations
end
class Timeline < ActiveRecord::Base
belongs_to :member
has_many :timeline_relations
has_many :videos, through: timeline_relations
end
class TimelineRelation < ActiveRecord::Base
belongs_to :timeline
belongs_to :video
end
关于ruby-on-rails - Ruby on Rails has_many 关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33501865/