【问题标题】:Scope with joins in Rails 4.2Rails 4.2 中的连接范围
【发布时间】:2015-10-20 01:09:55
【问题描述】:

我有类似的代码

class Article < ActiveRecord::Base
  has_many :comments
  scope :with_comments, joins(:comments)
end

基于this answer,但是当我在 Rails 4.2 中使用它时,我得到了

/Users/agrimm/.rbenv/versions/2.2.0/lib/ruby/gems/2.2.0/gems/activerecord-4.2.0/lib/active_record/scoping/named.rb:143:in `scope': The scope body needs to be callable. (ArgumentError)

Rails 4 和 Rails 4.2 之间关于允许范围内连接的规则是否发生了变化?我可以看到 4.2 release notes 中提到了联接,但我不知道它是否适用于此。

【问题讨论】:

标签: ruby-on-rails join named-scope ruby-on-rails-4.2


【解决方案1】:

您的语法错误。你应该这样做:

scope :with_comments, -&gt; { joins(:comments) }

你应该看看这个documentation

【讨论】:

    【解决方案2】:

    范围主体需要是可调用的。 (参数错误)

    这应该可行

    scope :with_comments, -> { joins(:comments) }
    

    一个很好的解释here

    【讨论】:

      【解决方案3】:

      你可以这样试试吗?

      scope :with_comments, -> { joins(:comments)}
      

      【讨论】:

        猜你喜欢
        • 2016-04-14
        • 2017-06-09
        • 2011-06-30
        • 2015-06-28
        • 1970-01-01
        • 2014-10-09
        • 2017-11-11
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多