2014-10-02 112 views
19

我有一個稱爲作者的模型。作者有很多文章。 文章有一個名爲.published的作用域:where(published:true)。Rails包含範圍

我想加載作者,與發表的文章。 我想:

Author.includes(:articles.published).find(params[:author_id]) 

但是,這將引發一個錯誤:未定義的方法 '發佈'。 有什麼想法?

+7

是的,這隻需要用一些不同的術語來搜索。這是「渴望加載範圍關聯」,請參閱:http://stackoverflow.com/questions/7937759/rails-3-activerecord-eager-loading-of-scope ...並且事實證明是重複的? – 2014-10-02 11:15:13

回答

1

試試這個代碼:

Author 
    .includes(:articles).where(published: true).references(:articles) 
    .find(params[:author_id]) 

在這裏你可以找到上面的例子中的詳細信息: includes api doc

15

我將指定的Author稱爲with_published_articles這樣一個範圍:

scope :with_published_articles, -> { joins(:articles).merge(Article.published) } 

這將解決您的問題,並在您的01上指定模型的情況下published行爲和Article將在未來發生變化。

所以現在你可以撥打:

Author.with_published_articles.find(params[:author_id]) 
24

我認爲最好的解決辦法是:

Author.includes(:articles).where(:articles=>{published: true}).find(params[:author_id]) 

或者你也可以創建範圍:

class Author < ActiveRecord::Base 
    scope :published_articles, -> { includes(:articles).where(articles: { published: true}) } 
end 

然後:

Author.published_articles.find(params[:author_id].to_s)