NothingToSeeHere NothingToSeeHere - 4 months ago 41
Ruby Question

rails 4 multiple ruby arrays with nested attributes

I'm trying to build a method that pulls an array of arrays, much like nested loops in the view.

I am trying to build a method on my User model that does this:

@past_parties = User.parties

<%= @past_parties.each do |past_party| %>
<%= past_party.guests("email").uniq.each do |guest| %>
<%= guest.name %> <%= guest.email %>
<% end %>
<% end %>


These are my models:

class User < ActiveRecord::Base

has_many :hosts, dependent: :destroy
has_many :parties, through: :hosts

def past_guests
self.parties.guests
end
end

class Host < ActiveRecord::Base
belongs_to :user
has_many :parties, dependent: :destroy
has_many :guests, through: :parties

end

class Party < ActiveRecord::Base

belongs_to :host
has_many :guests, dependent: :destroy

end

class Guest < ActiveRecord::Base

belongs_to :party

end


I can get the loop to work in the view, but when I try to build it as a method (so I can call current_user.past_guests, if current_user is an instance of User.), I get this error

undefined method `guests' for #<ActiveRecord::Associations::CollectionProxy []>


How do I get all of the guests that a user has ever invited without building the loop in the view?

Answer

The problem is that you're trying to access an array from another array:

self.parties.guests

self.parties returns an #<ActiveRecord::Associations::CollectionProxy []>, so if you want to get the guests of the parties you have to loop over the elements.

But since you want only the guests, you can simply change your user class to:

class User < ActiveRecord::Base

  has_many :hosts, dependent: :destroy
  has_many :parties, through: :hosts
  has_many :guests, through: :parties

  # Call your guests
  def past_guests
     self.guests 
  end
end