I have setup a model relationship and all is working well when I use code similar to:
@parent.child.each do |item|
item.name
end
But how would I call just a specific child given there id
eg.
Child ID is 14
Would like a call like:
@parent.child[childid].name #>>>>>> C开发者_StackOverflowHILD'S NAME
Try:
@parent.children.detect { |child| child.id == 14 }
This should return the object without querying the database. You can then call the .name
method on it.
@parent.child[14]
would most likely not work correctly, child
is an array, if it is a has_many
relation, but the array index is not the same as the id of the child. so you can do something like this:
@parent.child.find(14).name
I'm not really sure, but if you do something like this:
@parent = Parent.find(some_id, :include => :child)
@parent.child.find(some_other_id) # should hit the query cache
精彩评论