Rails包含范围 [英] Rails includes with scope
本文介绍了Rails包含范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个称为Author的模型。作者有很多文章。
文章的作用域称为.published,它的作用是:where(published:true)。
I have a model called Author. An author has many Articles. Articles have a scope called .published that does: where(published: true).
我想用已发布的文章来加载作者。
我尝试过:
I want to load the author, with the published articles. I tried:
Author.includes(:articles.published).find(params[:author_id])
但这会引发错误:未定义的方法已发布。
有什么想法吗?
But that throws an error: undefined method 'published'. Any idea?
推荐答案
我认为最好的解决方案是:
I think the best solution would be:
Author.includes(:articles).where(:articles=>{published: true}).find(params[:author_id])
或者您可以创建范围:
class Author < ActiveRecord::Base
scope :with_published_articles, -> { includes(:articles).where(articles: { published: true}) }
end
然后:
Author.with_published_articles.find(params[:author_id].to_s)
这篇关于Rails包含范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文