I have 2 models:
# models/car.rb
class Car < ActiveRecord::Base
belongs_to :model
end
and
# models/manufacturer.rb
class Manufacturer < ActiveRecord::Base
has_many :cars
end
When I’m executing command in rails console Car.find(1).manufacturer it shows me that one more sql query was executed SELECT manufacturers.* FROM manufacturers WHERE manufacturers.id = 54 LIMIT 1,
so I am interested is it usual (for production, first of all) behavior, when a lot of sql queries being executed just to get some object property? what about performance?
UPDATE, ANSWER:
I got an answer from another source: I was told it’s “necessary evil” as a payment for abstraction
This is not a “necessary evil” and your intuition that the second query is needless is correct. What you need to do is use
:include/includesto tell Rails to do aJOINto get the associated objects in the sameSELECT. So you could do this:Rails calls this “eager loading” and you can read more about it in the documentation (scroll down to or Ctrl+F for “Eager loading of associations”).
If you always want to eager-load the associated objects you can declare
default_scopein your model:However you shouldn’t do this unless you really need the associated Manufacturer every time you show a Car record.