Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"undefined method" for a rails model

I am using Devise with rails and i want to add a method "getAllComments", so i write this :

    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

And in my controller :

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

And when i go to my url, i got

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

What i am doing wrong?

Thank you

like image 541
Sebastien Avatar asked Oct 26 '11 09:10

Sebastien


2 Answers

Because getAllComments is a class method and you are attempting to access it as an instance method.

You either need to access it as:

User.getAllComments

or redefine it as an instance method:

class User < ActiveRecord::Base
  #...

  def getAllComments
    true
  end
end

def dashboard
  @user = current_user
  @comments = @user.getAllComments
end
like image 114
Douglas F Shearer Avatar answered Nov 15 '22 01:11

Douglas F Shearer


As I can see, you make getAllComments as class method through addition it to eigenclass. And you try to call this method from instance.

like image 38
WarHog Avatar answered Nov 15 '22 00:11

WarHog