【问题标题】:Rails 4, scope on related model loads all enties (scope doesn't filter)Rails 4,相关模型上的范围加载所有实体(范围不过滤)
【发布时间】:2015-04-19 08:08:51
【问题描述】:

我有这样的模型:

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

在 Rails 控制台上我尝试:

 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 进行了尝试,结果相同。

我做错了什么?

谢谢。

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-4 scope eager-loading


    【解决方案1】:

    这应该可以,您需要文章,但条件在帖子上

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

    使用只能从Post 模型访问的范围有一个更好的方法。

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

    【讨论】:

    • 但是要使用 Article.find(123).posts.where_author("guest").active 这样的链接,我仍然需要使用作用域和 lambdas 吗?
    • 如果active 是文章范围,则在关闭merge( ) 后使用它
    【解决方案2】:

    完整的解决方案(我在项目中使用的代码)是:

    关于文章

    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() 部分在这里非常重要。

    谢谢。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多