Mellon
Mellon

Reputation: 38902

Rails 3: Error when access Active Record model's attribute

I have a 'car' model which is a ActiveRecord:

class Car < ActiveRecord::Base
 ...
end

In the car table in DB, there is a column called 'available' which holds the boolean value. I try to access this value in the model class like:

class Car < ActiveRecord::Base
 ...
 if self.avaliable #error msg: undefined method 'available'

 end 
end

but I got error message "undefined method 'available'", why? how to access this attribute of the car model?

Upvotes: 0

Views: 580

Answers (3)

Mukesh Singh Rathaur
Mukesh Singh Rathaur

Reputation: 13135

In case you are calling this self.available form the class method of the class then first you will need to create the @car object of a Car class then you can easily call @car.available.

Otherwise if you are calling form an instance method of class, and the calling object is available there then self.available will work.

For more clarity on class methods Vs instance method and how to call them have look here. http://railstips.org/blog/archives/2009/05/11/class-and-instance-methods-in-ruby/

Upvotes: 0

Simone Carletti
Simone Carletti

Reputation: 176552

available (and not avaliable as you wrote in self.avaliable) is an instance methods and you can't access an instance method from a class.

From instance you can access instance methods and class methods but from the class you can't access instance methods because you need a valid instance.

Now the question is: what are you trying to do? We can probably provide a better answer if you let us know what you are trying to do.

Upvotes: 1

fl00r
fl00r

Reputation: 83680

You can't write ruby code inline in class body you should wrap it

if self.avaliable #error msg: undefined method 'available'

end 

as a method. And you can call it in before_filter

class Car < ActiveRecord::Base
  before_filter :check_avaliable

  def check_avaliable
    if self.avaliable 
      ...
    end 
  end
end

Upvotes: 0

Related Questions