【问题标题】:Rails polymorphic relationship in the other direction另一个方向的Rails多态关系
【发布时间】:2009-11-25 18:36:34
【问题描述】:

像这样设置了我的多态关系:

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 等等...

我正在努力做的是朝着另一个方向前进,即假设我想查找 Wine 的最后 10 条评论和 Beer 的最后 10 条评论。

【问题讨论】:

    标签: ruby-on-rails polymorphic-associations


    【解决方案1】:

    执行此操作的最简单方法可能是将命名范围添加到您的 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')
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-11-07
      • 1970-01-01
      • 2021-09-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多