Rails:模型关联和各自的控制器

时间:2017-01-09 23:24:05

标签: ruby-on-rails associations

我目前正在开发一个用户可以发布视频的应用程序。 视频可以有超过1个演员和超过1个类别。 演员可以有超过1个视频。 类别可以有超过1个视频。

我不太确定如何在模型之间设置关联。

另外,我应该为每个型号配备不同的控制器吗?

非常感谢!

2 个答案:

答案 0 :(得分:0)

通常,每个模型应该有一个不同的控制器,具体取决于你正在做什么。

我不建议使用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

答案 1 :(得分:0)

让我们从VideoActor开始。由于我们需要多对多关系,因此我们需要一个连接表。让我们调用连接表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至少有一个控制器,您的应用程序会为其公开路径。记住单一责任原则。请注意,这并不意味着每个模型都需要一个控制器,反之亦然 - 每个控制器都不需要模型。