Bye
Bye

Reputation: 768

Rails: Elegant way to find name from related model

I have to models:
Father has_many Children
f_name Child belongs_to Father c_name father_id(fk)

In children's index page I want to show c_name and fathers' name

<% @children.each do |child|%>
  <%= child.name %>
  <% if Father.find(child.father_id) %>
    <%= Father.find(child.father_id).f_name %>
  <% end %>
<% end %>

I do not think the code is elegant. Maybe I should put them into helper or model, but I do not know how to do that. Anybody help will be appreciated.

Upvotes: 0

Views: 39

Answers (2)

petecss
petecss

Reputation: 399

If you have your relationships correctly setup in your models then rails will give you some nice helper methods. In this case to find a child's father you can do: child.father. Then of course child.father.name to get the name of the father.

If you're worried that a child does not have a father then you could do something like:

<%= child.father.name if child.father %>

Upvotes: 1

Alex Kojin
Alex Kojin

Reputation: 5204

I'm not sure how your controller looks like, but it can be like this.

@children = Child.includes(:father)

in view:

<% @children.each do |child|%>
  <%= child.name %>
  <%= child.father.try(:name) %>
<% end %>

try does same as <%= child.father.name if child.father %>

Upvotes: 1

Related Questions