2016-07-17 8 views
1

私はCategoryモデルhas_manyLinkTextの投稿を持ち、それらの投稿は多く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 

が、私はそれらを取得するために、ハックの方法を使用しなければならないでしょう:

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

カテゴリをレポートに保存することをお勧めします。つまり、CategoryLink、または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 
関連する問題