开发者

Why did I get an ActiveRecord::Relation object?

开发者 https://www.devze.com 2023-02-21 00:56 出处:网络
I tried to get a car instance from database, theCar = Car.where(:name => \'TOYOTA\') puts theCar.user_name

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:

theCar = Car.where(:name => 'TOYOTA').first
# or
theCar = Car.first(:name => 'TOYOTA')
# or
theCar = Car.find_by_name('TOYOTA')

And if there is many Cars with name TOYOTA:

theCars = Car.where( :name => "TOYOTA" ).all
theCars.map(&:user_name)
#=> ["Jhon", "Paul" ...]
0

精彩评论

暂无评论...
验证码 换一张
取 消