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.
# parent.rb
has_many :children
# children.rb
belongs_to :parent
# 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)
.
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 %>