加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – rails 3 has_many through has_one

发布时间:2020-12-17 02:37:01 所属栏目:百科 来源:网络整理
导读:假设您有以下型号: class Category ActiveRecord::Base has_one :current_heat,class_name: 'Heat' has_many :scores,:through = :current_heatendclass Heat ActiveRecord::Base belongs_to :category has_many :scoresendclass Score ActiveRecord::Base
假设您有以下型号:

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.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读