轨道3的has_many通过HAS_ONE [英] rails 3 has_many through has_one

查看:144
本文介绍了轨道3的has_many通过HAS_ONE的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设你有以下型号:

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产生以下疑问:

Surprisingly, when I invoke Category.first.scores ActiveRecord produces the following queries:

SELECT `categories`.* FROM `categories` LIMIT 1
SELECT * FROM `scores` INNER JOIN `heats` ON `scores`.`heat_id` = `heats`.`id` WHERE `heats`.`category_id` = 1

上面的查询忽略了类别#current_heat 的HAS_ONE性质。我本来期望更多的东西,如:

The above query ignores the has_one nature of Category#current_heat. I would have expected something more like:

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。有人可以解释这种现象给我?有一种优雅的解决方法或一种正确的方式来做到这一点?

It's as if ActiveRecord is silently treating my has_one as a has_many. Can someone explain this behavior to me? Is there an elegant workaround or a "right way" to do it?

推荐答案

也许你可以删除

has_many :scores, :through => :current_heat

和,而不是仅仅代表:分数通过HAS_ONE:

and instead just delegate :scores through the has_one:

delegate :scores, :to => :current_heat

这将preserve所需的访问方法Category.first.scores。

that would preserve your desired access method Category.first.scores.

这篇关于轨道3的has_many通过HAS_ONE的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆