Why did I get an ActiveRecord :: Relation object?

I am trying to get a car instance from a database,

theCar = Car.where(:name => 'TOYOTA') puts theCar.user_name 

I received the error message: undefined method `` username '' for ActiveRecord :: Communication: 0xb6837b54

Why did I get an ActiveRecord :: Relation object, and not a Car . What could be the reason? By the way, I request a car inside the migration file. I am using Rails 3.

+4
source share
1 answer

You get it because you use Lazy Loading. Before calling a specific object or objects, nothing is loaded.

In fact, your query will return an array of objects: ALL cars named 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 are many cars named TOYOTA:

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

Source: https://habr.com/ru/post/1346195/


All Articles