[英]rails active record associations sql behavior
I have 2 models: 我有2个型号:
# 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
, 当我在rails控制台
Car.find(1).manufacturer
执行命令时,它向我显示另外一个sql查询被执行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? 所以我感兴趣的是它通常(对于生产,首先)的行为,当很多sql查询被执行只是为了得到一些对象属性? 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
. 你需要做的是使用
:include
/ includes
来告诉Rails做一个JOIN
来获取同一个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"). Rails称之为“急切加载”,你可以在文档中阅读更多关于它的信息 (向下滚动到或按Ctrl + F表示“渴望加载关联”)。
If you always want to eager-load the associated objects you can declare default_scope
in your model: 如果您总是希望加载关联对象,则可以在模型中声明
default_scope
:
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. 但是,除非您每次显示Car记录时确实需要关联的制造商,否则不应该这样做。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.