Akash
Akash

Reputation: 13

rails how to display data or retrieve values after find

I did a find on some model and got the following

>> @addy
=> [#<Address id: 3, street: "Some Street", houseNumber: nil, created_at: "2010-01-20 06:09:52", updated_at: "2010-01-20 06:09:52", address_id: 16>]

Now how do I retrieve the values? what if i want the street?

@addy.street does not work netiher does @addy[:street]

what if i had a list of @addy's and wanted to loop through them to show street for each?

Upvotes: 0

Views: 433

Answers (1)

MBO
MBO

Reputation: 31025

@addy.first.street should work, as it is list of Adress classes containing only one member.

For displaying each street for more adresses in list:

@addy.each do |address|
  puts address.street
end

or

list_of_streets = @addy.map { |address| address.street }

Edit:
When you have problem identifying what class you have, always check object.class. When you just use object in IRB, then you see output from object.inspect, which doesn't have to show class name or even can spoof some informations. You can also call object.methods, object.public_methods.

And remember that in Ruby some class is also an instance (of Class class). You can call @addr.methods to get instance methods and @addr.class.methods to get class methods.

Edit2:
In Rails #find can take as first parameter symbol, and if you pass :first of :last, then you'll get only one object. Same if you pass one integer (id of retrieved object). In other cases you get list as result, even if it contains only one object.

Upvotes: 4

Related Questions