Why can't I access attributes in rails model?

Hi, I’d like to know why I can’t, or how can I, access attributes like that:

class User < ActiveRecord::Base

def name

@first_name + @last_name

end

end

first_name and last_name are user attributes in the database.

Thanks in advance.

Have this instance variables been set anywhere in your app?

If not, you wont be able to access attributes anywhere.

I suggest to first find a record in the DB and set the results to and instance variable like:

@var = User.find(params[:some_params])

and then you will be able to access attributes for that object

@var.name + @var.lastname

ActiveRecord dynamically defines “accessor methods” on the

user instance.

That user instance is accessible as ‘self’ inside the user instance,

so you could do

class User < ActiveRecord::Base

def name

self.first_name + self.last_name

end

end

But, in Ruby, when using a read accessor, you could also write it

without the explicit ‘self’.

class User < ActiveRecord::Base

def name

first_name + last_name

same as self.first_name + self.last_name

if there is no first_name, last_name local variable

defined in the scope

end

end

For write accessors, you must put the self in front, that is:

self.full_name = “#{first_name} #{last_name}”

And the @first_name you asked about, that is an “instance variable”.

Read one of the many Ruby tutorials or books to understand this better.

HTH,

Peter

Thank you, but I knew that, I did that (use self to do what I want) before I asked the question.

I’d just like to know why can’t I use @first_name instead of self.first_name, to me it seems like the same thing inside the model.

They are not:

@first_name is an “instance variable”. You could set it like this:

@first_name = user.first_name

but it is not automatically set, and it is also not typically used like that.

A more typical use would be:

@user = User.find(params[:id])

and then you can use @user in the controller, but also in the views,

due to the set-up of Rails.

self.first_name is a method that is dynamically provided by

ActiveRecord , based on the available columns for the table

“users” in the database.

HTH,

Peter

I thought they where attr_accessor method.

Thank you for clearing things up for me.

I thought they where attr_accessor method.

Thank you for clearing things up for me.

To add a little more info, the attribute values are stored in the @attributes / @attributes_cache hashes

Fred