1

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?

2
  • you are calling instance method past_guests on User class, change the method to class method. Commented Jul 15, 2016 at 4:56
  • ah, no I wrote it wrong...I meant to say current_user.past_guests, not User.past_guests. I've fixed it. Commented Jul 15, 2016 at 5:01

2 Answers 2

1

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
Sign up to request clarification or add additional context in comments.

Comments

0

Each party is going to have collection of guests. You need to do this in your method definition:

def past_guests
  self.parties.collect(&:guests) 
end

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.