2010-08-29 65 views
0

我已经建立了模型关系,一切工作正常,当我使用类似代码:显示RoR的关系

@parent.child.each do |item| 
item.name 
end 

但我怎么会打电话只是一个特定的子给定的有ID

如。

儿童ID是14

想就像一个电话:

@parent.child[childid].name #>>>>>> CHILD'S NAME 

回答

0

@parent.child[14]很可能无法正常工作,child是一个数组,如果它是一个has_many关系,但数组索引不一样的孩子的身份证。所以你可以做这样的事情:

@parent.child.find(14).name 

我真的不知道,但如果你做这样的事情:

@parent = Parent.find(some_id, :include => :child) 
@parent.child.find(some_other_id) # should hit the query cache 
+0

这有效,但有没有其他方法可以做到这一点,然后再做更多的数据库调用? – Alex 2010-08-29 13:45:29

0

尝试:

@parent.children.detect { |child| child.id == 14 } 

这将返回对象而不查询数据库。然后你可以调用它的.name方法。