【问题标题】:Rails: undefined method Error when scopingRails:范围界定时未定义的方法错误
【发布时间】:2017-02-03 16:31:20
【问题描述】:

我有以下用户模型:

class User < ApplicationRecord
    # Associations
    has_many :issues
    # Instances
    def has_issues?
        issues.resolved.exists?
    end
end

和问题模型:

class Issue < ApplicationRecord
    # Associations
    belongs_to :user
    # Scopes
    scope :resolved, -> { where(:resolved => true) }
end

如果我现在在我的视图中调用类似:

unless current_user.has_issues

我收到以下错误:

控制器中的 NoMethodError#index
#<0x72dd7c0>

    标签: ruby-on-rails ruby methods scope ruby-on-rails-5


    【解决方案1】:

    范围是您在类(例如 User.has_issues)或 ActiveRecord::Relation(例如 User.where(...).has_issues)上调用的方法。您不能在模型的实例上调用范围方法。如果你想获取模型实例的信息,你应该使用实例方法,而不是作用域:

    class User < ApplicationRecord
      has_many :issues
    
      def has_issues?
        issues.resolved.exists?
      end
    end
    

    【讨论】:

    • 您能否编辑您的问题以包含您更新的代码? (请注意,根据 Ruby 约定,我的代码在方法名称的末尾有一个问号,因此请务必考虑到这一点。)
    • 当你调用方法时你是在调用has_issues?还是has_issues?
    • 我在调用该方法时忘记附加问号。感谢您的帮助!
    猜你喜欢
    • 2012-05-11
    • 2011-11-28
    • 2017-07-26
    • 1970-01-01
    • 2013-12-27
    • 1970-01-01
    • 2012-12-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多