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 belongs_to :heatend
令人惊讶的是,当我调用category.first.scores时,ActiveRecord会产生以下查询:
SELECT `categorIEs`.* FROM `categorIEs` liMIT 1SELECT * 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 1SELECT `heats`.* FROM `heats` WHERE `heats`.`category_ID` = 1 liMIT 1SELECT * 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.
总结以上是内存溢出为你收集整理的ruby-on-rails – rails 3 has_many through has_one全部内容,希望文章能够帮你解决ruby-on-rails – rails 3 has_many through has_one所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)