运维开发网

ruby-on-rails – rails 3 has_many through has_one

运维开发网 https://www.qedev.com 2020-06-09 16:54 出处:网络 作者:运维开发网整理
假设您有以下型号: 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 ha
假设您有以下型号:

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, :to => :current_heat

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

0

精彩评论

暂无评论...
验证码 换一张
取 消