Seb*_*ien 5 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
Run Code Online (Sandbox Code Playgroud)
在我的控制器中:
def dashboard
@user = current_user
@comments = @user.getAllComments();
end
Run Code Online (Sandbox Code Playgroud)
当我去我的网址时,我得到了
undefined method `getAllComments' for #<User:0x00000008759718>
Run Code Online (Sandbox Code Playgroud)
我做错了什么?
谢谢
因为getAllComments是一个类方法,并且您尝试将其作为实例方法进行访问.
您需要访问它:
User.getAllComments
Run Code Online (Sandbox Code Playgroud)
或者将其重新定义为实例方法:
class User < ActiveRecord::Base
#...
def getAllComments
true
end
end
def dashboard
@user = current_user
@comments = @user.getAllComments
end
Run Code Online (Sandbox Code Playgroud)