shou2017.com
JP

Calling values from a table in a has_many relationship in a view

Sat Aug 12, 2017
Sat Aug 10, 2024

What we want to do.

I want to display the parent and children in the has_many relationship on the listing page. There was a similar question, but just a note here.

Model

# parent.rb
has_many :children
# children.rb
belongs_to :parent

controller

# parent.controller
def index
 @parents = Parent.includes(:children).all
end

The includes method is used to retrieve all related models at once. The syntax is includes(related name).

view

I want to display the last name of the parent (LAST_NAME) and the first name of the child (FIRST_NAME).

# index.html.erb
<% @parents.each  do |parent| %>
 <%= parent.last_name %>

  <% parent.children.each  do |child| %>
    <%= child.first_name %>
  <% end  %>

<% end %>
See Also