正确使用多态关联报告

时间:2016-07-17 14:35:05

标签: ruby-on-rails ruby

我有一个Category模型has_many LinkText个帖子,这些帖子有很多Report个。

如何使用@category.reports最好地设置模型/架构以检索该类别的所有报告?我的基础是文档中的示例:

class Category < ActiveRecord::Base
  has_many :link_posts, class_name: "Link"
  has_many :text_posts, class_name: "Text"
end

class Link < ActiveRecord::Base
  belongs_to :category
  has_many :reports, as: :reportable
end

class Text < ActiveRecord::Base
  belongs_to :category
  has_many :reports, as: :reportable
end

class Report < ActiveRecord::Base
  belongs_to :reportable, polymorphic: true
end

如果我这样做,我将不得不使用hacky方法来检索它们:

class Category < ActiveRecord::Base
  def reports
    reports = []

    reports << Report.where(reportable: self.link_posts.to_a)
    reports << Report.where(reportable: self.text_posts.to_a)

    reports
  end
end

正确的方法是什么?

1 个答案:

答案 0 :(得分:0)

我建议您在报告中存储类别 - 这样您就可以根据CategoryLinkText查看所有类别。将许多项目联系在一起并没有真正的危害。

class Category < ActiveRecord::Base
  has_many :link_posts, class_name: "Link"
  has_many :text_posts, class_name: "Text"
  has_many :reports, as: :reportable
end

class Link < ActiveRecord::Base
  belongs_to :category
  has_many :reports, as: :reportable
end

class Text < ActiveRecord::Base
  belongs_to :category
  has_many :reports, as: :reportable
end

class Report < ActiveRecord::Base
  belongs_to :category
  belongs_to :reportable, polymorphic: true
end