假设您有以下模型:
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
上面的查询忽略了 has_one 的性质Category#current_heat
。我本来期望的更像是:
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
仅当您使用 . 从根显式遍历 has_one 关联时才会生成Category.first.current_heat.scores
。
就好像 ActiveRecord 默默地将我的 has_one 视为 has_many。有人可以向我解释这种行为吗?是否有一个优雅的解决方法或“正确的方法”来做到这一点?