以下是相关事实:
每个
主题
有很多
评论
。Comment
模型有一个名为very_popular
的范围
,我们假设它涉及比较其多个列。def self.very_popular # lots of cool stuff end
Topic
模型有一个名为exciting
的scope
,其中包括具有的所有
topic
>very_popular评论
。
第三点是我陷入困境的地方。下面的结果是缺少方法异常,虽然听起来很可怜,但我不知道还能尝试什么!
def self.exciting
join(:comments).very_popular
end
如何在 Topic
模型范围中重用 Comment
模型中的 very_popular
范围?
最佳答案
您不能直接使用其他模型的范围。您可以做的就是合并查询。
Topic.joins(:comments).merge(Comment.very_popular)
Ryan 在这里进行了精彩的解释:http://railscasts.com/episodes/215-advanced-queries-in-rails-3
关于ruby-on-rails - 在 Rails 3 中通过范围和关联保持 DRY,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6742433/