gpt4 book ai didi

ruby-on-rails - rails 3 has_many 到 has_one

转载 作者:行者123 更新时间:2023-12-04 05:59:10 25 4
gpt4 key购买 nike

假设您有以下模型:

class Category < ActiveRecord::Base
has_one :current_heat, class_name: 'Heat'
has_many :scores, :through => :current_heat
end

class Heat < ActiveRecord::Base
belongs_to :category
has_many :scores
end

class Score < ActiveRecord::Base
belongs_to :heat
end

令人惊讶的是,当我调用 Category.first.scores ActiveRecord 产生以下查询:
SELECT `categories`.* FROM `categories` LIMIT 1
SELECT * FROM `scores` INNER JOIN `heats` ON `scores`.`heat_id` = `heats`.`id` WHERE `heats`.`category_id` = 1

上面的查询忽略了 Category#current_heat 的 has_one 特性。 .我本来期望的更像是:
SELECT `categories`.* FROM `categories` LIMIT 1
SELECT `heats`.* FROM `heats` WHERE `heats`.`category_id` = 1 LIMIT 1
SELECT * FROM `scores` WHERE `scores`.`heat_id` = 6

仅当您使用 Category.first.current_heat.scores 从根显式遍历 has_one 关联时才会生成。 .

就好像 ActiveRecord 默默地将我的 has_one 视为 has_many。有人可以向我解释这种行为吗?是否有一个优雅的解决方法或“正确的方法”来做到这一点?

最佳答案

也许你可以删除

has_many :scores, :through => :current_heat

而是通过 has_one 委托(delegate) :scores:
delegate :scores, :to => :current_heat

这将保留您所需的访问方法 Category.first.scores。

关于ruby-on-rails - rails 3 has_many 到 has_one,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12606212/

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