Rails 另一个方向的多态关系
像这样建立我的多态关系:
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
最简单的方法可能是向您的
Review
模型添加一个指定reviewable_type
列的命名范围。像这样:
这样您在查找结果时就可以灵活地确定范围......
等等
The easiest way to do this is probably to add a named scope to your
Review
model that specifies thereviewable_type
column.Like so:
That way you have the flexibility of scoping when finding your results...
etc