Ruby-on-rails Rails 包括范围
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26159533/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Rails includes with scope
提问by MonsieurNinja
I have a model called Author. An author has many Articles. Articles have a scope called .published that does: where(published: true).
我有一个名为 Author 的模型。一个作者有很多文章。文章有一个名为 .published 的范围,它的作用是: 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?
但这会引发错误:未定义的方法“已发布”。任何的想法?
回答by NikCasper
I think the best solution would be:
我认为最好的解决方案是:
Author.includes(:articles).where(:articles=>{published: true}).find(params[:author_id])
Or you can create scope:
或者您可以创建范围:
class Author < ActiveRecord::Base
scope :with_published_articles, -> { includes(:articles).where(articles: { published: true}) }
end
and then:
进而:
Author.with_published_articles.find(params[:author_id].to_s)
回答by Manuel van Rijn
I would specify a scope on the Authorcalled with_published_articleslike this:
我会像这样指定一个被Author调用的范围with_published_articles:
scope :with_published_articles, -> { joins(:articles).merge(Article.published) }
This will resolve your problem to also specify the where(active: true)on your Authormodel in case the publishedbehaviour of and Articlewill change in the future.
这将解决您的问题,并where(active: true)在您的Author模型上指定,以防将来published和的行为Article发生变化。
So now you can call:
所以现在你可以调用:
Author.with_published_articles.find(params[:author_id])
回答by max_spy
Try this code:
试试这个代码:
Author
.includes(:articles).where(published: true).references(:articles)
.find(params[:author_id])
Here you can find more information about the example above: includes api doc
在这里您可以找到有关上述示例的更多信息: includes api doc
回答by Wagner Caixeta
Using:
使用:
class Articles < ActiveRecord::Base
scope :published, -> { where(articles: {published: true}) }
end
Define a scope on Autor
在 Autor 上定义范围
class Author < ActiveRecord::Base
scope :with_published_articles, -> { joins(:articles).merge(Articles.published) }
end
Or
或者
Author.joins(:articles).merge(Articles.published).find(params[:author_id])

