开发者

Displaying RoR relationship

开发者 https://www.devze.com 2023-01-14 02:39 出处:网络
I have setup a model relationship and all is working well when I use code similar to: @parent.child.each do |item|

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
0

精彩评论

暂无评论...
验证码 换一张
取 消