2015-04-19 304 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()这里的一部分非常重要。

谢谢。