【发布时间】:2012-09-18 08:14:49
【问题描述】:
假设您有以下模型:
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。有人可以向我解释这种行为吗?有没有优雅的解决方法或“正确的方法”?
【问题讨论】:
标签: ruby-on-rails activerecord has-many-through