rails active record associations sql behavior
I have 2 models:
# models/car.rb
class Car < ActiveRecord::Base
belongs_to :model
end
and
# models/m开发者_Go百科anufacturer.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
/includes
to tell Rails to do a JOIN
to get the associated objects in the same SELECT
. So you could do this:
Car.find 1, :include => :manufacturer
# or, in Rails 3 parlance:
Car.includes(:manufacturer).find 1
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_scope
in your model:
class Car
belongs_to :manufacturer
default_scope :include => :manufacturer
# or Rails 3:
default_scope includes(:manufacturer)
end
However you shouldn't do this unless you really need the associated Manufacturer every time you show a Car record.
精彩评论