I tried to get a car instance from database,
theCar = Car.where(:name => 'TOYOTA')
puts theCar.user_name
I got the error message: undefined method `user_name’ for
ActiveRecord::Relation:0xb6837b54
Why did I get an ActiveRecord::Relation object, and not a Car object?? What could be the cause? By the way, I queried the car inside my migration file. I am using Rails 3.
You get it because you are using Lazy Loading. Nothing is loaded before you will call certain object or objects.
As a matter of fact your query will return an Array of objects: ALL cars with a name TOYOTA. If you know that there is only one CAR with this name you can do this:
And if there is many Cars with name TOYOTA: