我有一个Category
模型has_many
Link
和Text
个帖子,这些帖子有很多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
正确的方法是什么?
答案 0 :(得分:0)
我建议您在报告中存储类别 - 这样您就可以根据Category
,Link
或Text
查看所有类别。将许多项目联系在一起并没有真正的危害。
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