Rails 另一个方向的多态关系

发布于 2024-08-12 06:34:52 字数 441 浏览 6 评论 0原文

像这样建立我的多态关系:

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

我正在努力做的是朝另一个方向走,即可以说我想要查找葡萄酒的最新 10 条评论和啤酒的最新 10 条评论。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

格子衫的從容 2024-08-19 06:34:52

最简单的方法可能是向您的 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')

等等

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文