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.
An instance of ActiveRecord::Base is an object that represents a specific row of your database (or might be saved into the database). Whereas an instance of ActiveRecord::Relation is a representation of a query that can be run against your database (but wasn't run yet).
ActiveRecord::Base indicates that the ActiveRecord class or module has a static inner class called Base that you're extending.
What is ActiveRecord? ActiveRecord is an ORM. It's a layer of Ruby code that runs between your database and your logic code. When you need to make changes to the database, you'll write Ruby code, and then run "migrations" which makes the actual changes to the database.
ActiveRecord expects applications to follow certain naming conventions. These conventions extend from file naming, class naming, table naming and more. By default classes are singular, tables are plural, primary keys are id and foreign keys are table_id.
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" ...]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With