Question

I'm trying to find the value of a particular model's attribute in rails. Here's what my code in the User controller's 'create' method looks like:

@user = User.find(1, :select => :money)
existing_money = @user
puts "#{existing_money}"

In my Heroku logs I'll see a variant of the following output instead of the :money integer for that particular user (with :id 1)

#<User:0x00000004e7cbc0>

Any thoughts? Thanks!

Était-ce utile?

La solution

As existing_money is just the object you are seeing the object's ID.
As you want the money attribute you have to reference that too.

puts "#{existing_money.money}"

Autres conseils

@user = User.find(1, :select => :money)

You are setting the @user instance variable with an object that has only one value, namely the money value. For now, all this does is save you a few bytes, by leaving off things like id, email, and any other columns you have in that table. It does however still return an object with attributes, the only difference is your object has only one attribute to call.

existing_money = @user

Given that @user is still an object with a single attribute, you now save this object in the existing_money local variable. What you probably want to do is *only store the money attribute in this variable`.

So you'd need this:

existing_money = @user.money

puts "#{existing_money}"

After the above change, this puts statement should return the attribute value, not the object encapsulating the attribute.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top