문제

Having set up my polymorphic relationship like so:

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

I can do Wine.last.reviews and Beer.find(3).reviews etc...

What I'm strugling to do is go in the other direction, i.e. Lets say I want to find the last 10 reviews for Wine and the last 10 reviews for Beer.

도움이 되었습니까?

해결책

The easiest way to do this is probably to add a named scope to your Review model that specifies the reviewable_type column.

Like so:

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

That way you have the flexibility of scoping when finding your results...

Review.for_wines.approved.all
Review.for_beers.active.find(:all, :order => 'created_at')

etc

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top