rails 3 has_many通过has_one

mga*_*dda 4 activerecord ruby-on-rails has-many-through

假设您有以下型号:

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
Run Code Online (Sandbox Code Playgroud)

令人惊讶的是,当我调用Category.first.scoresActiveRecord时会产生以下查询:

SELECT `categories`.* FROM `categories` LIMIT 1
SELECT * FROM `scores` INNER JOIN `heats` ON `scores`.`heat_id` = `heats`.`id` WHERE `heats`.`category_id` = 1
Run Code Online (Sandbox Code Playgroud)

上面的查询忽略了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
Run Code Online (Sandbox Code Playgroud)

只有当您从根目录显式遍历has_one关联时才会生成Category.first.current_heat.scores.

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

njo*_*den 5

也许你可以删除

has_many :scores, :through => :current_heat
Run Code Online (Sandbox Code Playgroud)

而只是委托:通过has_one得分:

delegate :scores, :to => :current_heat
Run Code Online (Sandbox Code Playgroud)

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