Question

I'm building a guestlist app and I have defined both Guest (name) and List models - guests can have many lists and lists can have many guests. Both are associated in a has_many through association (after reading that HABTM associations aren't a good idea).

Here are my models:

class Guest < ActiveRecord::Base
    has_many :lists, through: :checklists
end

class List < ActiveRecord::Base
    has_many :guests, through: :checklists
end

class Checklist < ActiveRecord::Base
    belongs_to :list
    belongs_to :guest
end

EDIT - my lists controller for show:

  def show
    @list = List.find(params[:id])
  end

On the List show view, I want to display the all of the guest names that are tied to that list through the checklist table. I can figure out if I need a do loop or an array...this is a bit beyond my current skill.

I've tried things like the following:

<%= @list.checklist.guest.name %>

I'm clearly missing some key bit of code and concept here.

Thanks in advance.

Était-ce utile?

La solution

You need to iterate over guests like this:

<% @list.guests.each do |guest| %> # For each guest in list.guests
  <%= guest.name %> # print guest.name
<% end %>

Autres conseils

It should be something like this

<% @list.guests.each do |guest| %>
  <%= guest.name %>
<% end %>
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top