ruby - "undefined method"用于 rails 模型

标签 ruby ruby-on-rails-3

我正在使用带有 Rails 的 Devise,我想添加一个方法“getAllComments”,所以我这样写:

    class User < ActiveRecord::Base
      # Include default devise modules. Others available are:
      # :token_authenticatable, :encryptable, :confirmable, :lockable, :timeoutable and :omniauthable
      devise :database_authenticatable, :registerable,
             :recoverable, :rememberable, :trackable, :validatable

      # Setup accessible (or protected) attributes for your model
      attr_accessible :email, :password, :password_confirmation, :remember_me, :city, :newsletter_register, :birthday, :postal_code,
          :address_complement, :address, :lastname, :firstname, :civility

      has_many :hotels_comments

      class << self # Class methods
          def getAllComments
             true
          end
      end
    end

在我的 Controller 中:

def dashboard
  @user = current_user
  @comments = @user.getAllComments();
end

当我访问我的 url 时,我得到了

 undefined method `getAllComments' for #<User:0x00000008759718>

我做错了什么?

谢谢

最佳答案

因为 getAllComments 是一个类方法,而您正试图将其作为实例方法访问。

您要么需要访问它:

User.getAllComments

或者重新定义为实例方法:

class User < ActiveRecord::Base
  #...

  def getAllComments
    true
  end
end

def dashboard
  @user = current_user
  @comments = @user.getAllComments
end

关于ruby - "undefined method"用于 rails 模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7901001/

相关文章:

ruby-on-rails - 从 Rails 在本地机器上执行命令

带有 win32ole 的 Ruby 程序在 Windows 7 64 位下不再工作

ruby-on-rails - 在哪里存储不属于模型或 Controller 的代码?

Ruby,以正确的顺序迭代对象数组

ruby - 使用参数与 ruby​​ require

testing - 在测试环境中自动运行 gem 任务

ruby-on-rails - 没有模型的 Google-maps-for-Rails

ruby-on-rails - S3 方法是同步的吗?

ruby-on-rails - 如何在ActiveAdmin中自定义默认登录页面?

ruby-on-rails-3 - 在 Rails 中通过用户名更正短 url 的路由