他の方向における多型の関係レール
-
22-09-2019 - |
質問
ので、私のように多型の関係を設定した。
class Review < ActiveRecord::Base
belongs_to :reviewable, :polymorphic => true
belongs_to :user
end
class Wine < ActiveRecord::Base
has_many :reviews, :as => :reviewable
end
class Beer < ActiveRecord::Base
has_many :reviews, :as => :reviewable
end
私はWine.last.reviewsとBeer.find(3).reviewsなどを行うことができます...
私は何をstruglingてることはつまり、私はワインとビールのための最後の10はレビューのために、最後の10件のレビューを見つけたいとしましょう、他の方向に行くです。
解決
これを行う最も簡単な方法は、Review
列を指定するあなたのreviewable_type
モデルに名前の範囲を追加することはおそらくあります。
のようなので:
class Review < ActiveRecord::Base
belongs_to :reviewable, :polymorphic => true
belongs_to :user
named_scope :for_wines, :conditions => { :reviewable_type => 'Wine' }
named_scope :for_beers, :conditions => { :reviewable_type => 'Beer' }
end
あなたは結果を見つけたときにスコーピングの柔軟性を持ってそのように...
Review.for_wines.approved.all
Review.for_beers.active.find(:all, :order => 'created_at')
など
所属していません StackOverflow