2015-04-19 308 views
1

我有車型像:軌道4,對相關模型範圍加載所有enties(範圍不過濾)

class Post < AvtiveRecord::Base 
    belongs_to :article 
    default_scope { order(created_at: :desc) } 
    scope :active, -> { where(active: true).order(created_at: :desc) } 
    scope :where_author, -> (author) { where("author LIKE ?", "#{author}%") } 
end 

class Article < ActiveRecord::Base 
    has_many :posts, dependent: :destroy 
end 

當軌控制檯上我嘗試:

Article.find(123).posts.where_author("guest") 

我得到預期值。

但是當我這樣做在ArticlesController:

@articles = Article.includes(:posts).posts.where_author("guest") # I will use params array when it work 

這會將所有文章,而忽略範圍的條件下,實際的SQL查詢完全不包括範圍的一部分。

我試過joinsincludes,結果相同。

我在做什麼錯了?

謝謝。

回答

0

這應該工作,你需要的文章,但條件是在後

Article.joins(:posts).where('posts.author like ?', 'guest%') 

有一個更好的方式來做到這一點使用這就是從Post模型只訪問範圍。

Article.joins(:posts).merge(Post.where_author('guest')) 
+0

但要使用鏈接像 'Article.find(123).posts.where_author(「guest」).active' 我仍然必須使用範圍和lambdas? – rolkos

+0

如果'active'是一個文章範圍,那麼在關閉merge()後使用它 –

0

完整的解決方案(代碼我在項目中使用)是:

對第

scope :post_author, -> (author) { joins(:posts).merge(Post.where_author(author)) } 
上發表

scope :where_author, -> (author) { where("posts.author LIKE ?", "#{author}%") } 

現在我可以使用範圍,並把它們連爲如下:

@articles = Article.post_author(params[:post_author]) 

merge()這裏的一部分非常重要。

謝謝。