2
votes

My question has to do with Associations. Forgive me as I am just learning this.

I have two tables (parent & child). I have set up the associations where the parent table is set to has_many children and the child table has one parent with foriegn id set to parent_id. This is working fine.

My question is that I want to create a family view that shows both parents and children together and associated with each other. So it would look like this:

Parent Name

  • Child Name
  • Child Name

I am pretty sure I need to create a family table and do a has_and_belongs_to_many association but not sure how to show the two together like above Hope this makes sense.

2
I think something went wrong with your association if you define in your child model child has one parent then child_id should be foreign key in your parents table .Antima Gupta

2 Answers

2
votes

If you just want to show parents and their children at view you don't need to create new table, just do as below:

In your Parents controller's index action( I am considering that you want to show all the parents with their children so I am using index action ) :

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

Then on your index.html.erb view :

<% @parents.each do |parent| %>
  <%= parent.name%><br/>
  <% parent.children.each do |child| %>
    <%= child.name%><br/>
  <% end %>
<% end %>

Considering that you have define association between you Parent an Child model

0
votes
class Parent
 has_many :children
end

class Child
 belongs_to :parent
end 

In controller

@parent = Parent.find(params[:id]).includes(:children)

In view

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