我正在使用带有 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/