gpt4 book ai didi

mysql - Rails 事件记录关联 SQL 行为

转载 作者:行者123 更新时间:2023-11-29 09:03:38 26 4
gpt4 key购买 nike

我有 2 个模型:

# models/car.rb
class Car < ActiveRecord::Base
belongs_to :model
end

# models/manufacturer.rb
class Manufacturer < ActiveRecord::Base
has_many :cars
end

当我在rails控制台中执行命令时Car.find(1).manufacturer它显示我又执行了一个 sql 查询 SELECT manufacturers.* FROM manufacturers WHERE manufacturers.id = 54 LIMIT 1 ,

所以我感兴趣的是,当执行大量 SQL 查询只是为了获取某些对象属性时,这是否是常见的(首先是生产)行为?性能怎么样?

更新,答案:我从另一个来源得到了答案:我被告知这是“必要的邪恶”作为抽象的支付

最佳答案

这不是“必要的邪恶”,您认为第二个查询是不必要的直觉是正确的。您需要做的是使用 :include/includes 告诉 Rails 执行 JOIN 来获取同一 中的关联对象选择。所以你可以这样做:

Car.find 1, :include => :manufacturer

# or, in Rails 3 parlance:

Car.includes(:manufacturer).find 1

Rails 将此称为“渴望加载”,您可以 read more about it in the documentation (向下滚动到“提前加载关联”或按 Ctrl+F)。

如果您总是想要立即加载关联的对象,您可以声明 default_scope在你的模型中:

class Car
belongs_to :manufacturer

default_scope :include => :manufacturer

# or Rails 3:

default_scope includes(:manufacturer)
end

但是,除非您确实每次显示汽车记录时都需要关联的制造商,否则您不应该这样做。

关于mysql - Rails 事件记录关联 SQL 行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7757987/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com