user3456978
user3456978

Reputation: 248

Rails has_many and belongs to twice in single view

In my database a sock has_many shoes. A shoe has_many shoelaces.

  create_table "socks", force: :cascade do |t|
    t.string   "sock_name"
  end

  create_table "shoes", force: :cascade do |t|
    t.integer  "sock_id"
    t.string   "shoe_name"
  end

  create_table "shoelaces", force: :cascade do |t|
    t.integer  "shoe_id"
    t.integer  "shoelace_name"
  end

In the socks view I want to display all the shoes a sock owns, and all shoelaces a shoe owns.

In my controller I have:

def show
  @sock = Sock.find(params[:id])
  @shoes = @sock.shoes
  @shoelaces = Shoelace.where(shoe: @shoes)
end

I'm running something like this now:

<% @shoes.each do |shoe| %>     
  <%= shoe.shoe_name %>
  <%= Shoelace.where(shoe: shoe).shoelace_name %>
<% end %>

How can I display my shoelaces belonging to my shoes inside of a .each so that they are together in my view without have a query outside of the controller? Would this method apply if my shoelace has_many strings?

Upvotes: 0

Views: 37

Answers (1)

Shannon
Shannon

Reputation: 3018

You can have something in your Shoe model such as:

def shoelaces_for_shoe
  Shoelace.where(shoe_id: id).shoelace_name
end

Then in your view:

<% @shoes.each do |shoe| %>     
  <%= shoe.shoe_name %>
  <%= @shoe.shoelaces_for_shoe %>
<% end %>

Upvotes: 1

Related Questions