我目前正在研究一个用户可以发布视频的应用程序。 视频可以有超过1个演员和超过1个类别。 演员可以有超过1个视频。 类别可以有多个视频。Rails:模型协会和各自的控制器
我不太确定如何设置模型之间的关联。
另外,我应该为每个模型有不同的控制器?
非常感谢!
我目前正在研究一个用户可以发布视频的应用程序。 视频可以有超过1个演员和超过1个类别。 演员可以有超过1个视频。 类别可以有多个视频。Rails:模型协会和各自的控制器
我不太确定如何设置模型之间的关联。
另外,我应该为每个模型有不同的控制器?
非常感谢!
让我们从Video
和Actor
开始。既然我们想要一个多对多的关系,我们需要一个连接表。让我们调用连接表roles
并为其创建一个模型。
class Video < ApplicationRecord
has_many :roles
has_many :actors, though: :roles
end
class Actor < ApplicationRecord
has_many :roles
has_many :videos, though: :roles
end
class Role < ApplicationRecord
belongs_to :actor
belongs_to :video
end
我们可以应用相同的逻辑来分类:
class Video < ApplicationRecord
has_many :roles
has_many :actors, though: :roles
has_many :categorizations
has_many :categories, through: categorizations
end
class Category < ApplicationRecord
has_many :categorizations
has_many :video, through: categorizations
end
class Categorization < ApplicationRecord
belongs_to :video
belongs_to :category
end
另一种方式做,这是通过使用has_and_belongs_to_many
它不需要加入模型,但has many limitations。为角色使用专用模型使得例如添加角色的名称变得微不足道,并允许您直接查询表。
如果您希望类别能够应用于多种模型,您也可以使用polymorphism。
另外,我应该为每个模型有不同的控制器?
一个好的经验法则是每个resource至少有一个控制器,您的应用程序公开路由。记住单一责任原则。请注意,这并不意味着每个模型都需要一个控制器,反之亦然 - 每个控制器都不需要一个模型。
一般来说,每个模型应该有不同的控制器,具体取决于你在做什么。
我不会建议使用has_and_belongs_to_many
。有很多文章指出使用它时的调试困难。简单的谷歌搜索应该可以解释为什么。相反,使用连接表。
video.rb
has_many :actors, through: :video_actors
has_many :video_actors
has_many :categories, through: :video_categories
has_many :video_categories
video_categories.rb
belongs_to :video
belongs_to :category
video_actors.rb
belongs_to :video
belongs_to :actor
actor.rb
has_many :videos, through: :video_actors
has_many :video_actors
category.rb
has_many :videos, through: :video_categories
has_many :video_categories
它是一个相当不错的答案。但是,如果您使用'class Video ... end'并缩进内容而不是每个文件的文件名,它会更具可读性。 – max
你怎么知道他使用Rails 5来确保ApplicationRecord能够工作?也许我错过了一些东西,但在原始问题中没有澄清。 –
我的确在使用Rails 5;我忘了提及它。 –
@DarioBarrionuevo幸运的猜测。 – max