2014-10-16 68 views
0

我有Parent谁拥有很多Children,但只有一个FirstbornFirstbornChild与“长子”的相关ChildTypeRails 4:父has_one具有特定相关子类型的子项

class Parent 
    has_many :children 
    has_one :firstborn, -> { includes(:child_type).references(:child_type).where("child_type.name = ?", "firstborn") }, class_name: "Child" 
end 

class Child 
    belongs_to :parent 
    belongs_to :child_type 
end 

class ChildType 
    has_many :children 
end 

下面的代码确实工作:

parent = Parent.find(1)  # => <parent object> 
firstborn = parent.firstborn # => nil 

的最终目标是能够检索所有家长和初生儿的孩子在1个查询。

parents_and_firstborn = Parent.includes(:firstborn) 

我在寻找一个只执行1个查询和检索Parent及相关Firstborn孩子的解决方案。

我已经回顾了有关has_one的Rails 4.0.2 API文档,但是他们的示例 没有一个像我想要做的那样跨越多个表。

更新:2014年10月16日14:40

下面的 “作品”,但我不知道为什么:

parent = Parent.includes(:firstborn).find(1) # => <parent with firstborn>

为什么我不能检索firstborn AFTER我已经检索到Parent,但是如果我在原始查询中返回它includes(...)吗?

解决方案:2014年10月16日14:50

我有一个attr_accessor :firstborn还停留在以前的尝试是解决这一问题的Parent模型。当我删除未使用的代码时,has_one :firstborn ...代码按预期工作。

回答

1

看起来是正确的(ish),你应该调试正在执行的SQL。

我真的质疑ChildType表的优点,从我在这里看到的。你的模式看起来过于复杂。你为什么不使用firstbborn布尔?

+0

我很乐意使用替代模式设计......但是,我正在使用遗留系统,我无法对其进行更改。相信我,我已经尝试了几个月,因为这个问题以及许多其他问题。对于特定的问题,我可能需要查询/过滤多个ChildTypes。 – 2014-10-16 18:32:28

+0

如果显示两种情况下返回的SQL;我们可能会有更好的运气来帮助您调试。 – 2014-10-16 18:45:20

+0

哦...我发现了问题。我现在觉得很蠢!当我正在处理这个问题时,在我决定使用'has_one'关联之前,我创建了一个'attr_accessor:firstborn'。该访问器方法是返回'nil'的。一旦我删除了,上面的代码实际上按预期工作。我讨厌传统系统! – 2014-10-16 18:51:58

相关问题