简体   繁体   中英

Rails: Show all associated records on a has_many through association

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.

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 %>

It should be something like this

<% @list.guests.each do |guest| %>
  <%= guest.name %>
<% end %>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM