Jay
Jay

Reputation: 6244

Rails 3 noob - difficulty populating an array

UPDATED WITH SOLUTION FROM BELOW PRODUCES NEW ERROR.

Users invite others to review their work. To track this, the invitations table has reviewer_id and reviewee_id fields. The model contains:

belongs_to :user
has_many :users

To display all invitations for a user we first get all the invitations:

@invitations = Invitation.where("reviewee_id = ?", current_user.id ).select(:reviewer_id).order("updated_at")

Then we get all the users who were invited: (this part is wrong)

@reviewers = []
@invitations.each do |i|
  @reviewers << User.where("id = ?", i.reviewer_id )
end

This current solution produces the following:

undefined method `first_name' for []:ActiveRecord::Relation

I did a test with the following code to see what is in @reviewers:

<% @reviewers.each do |r| %>
   <%= r.id %><br>
<% end %>

Instead of returning the ids it returned:

2173491700
2173491200
2173490540

So the array is not getting populated appropriately.

I am grateful for your help and most grateful for specific code.

Upvotes: 1

Views: 531

Answers (2)

Douglas F Shearer
Douglas F Shearer

Reputation: 26488

You want to gather up all the IDs then pass them to where.

reviewer_ids = @invitations.collect { |i| i.reviewer_id }
@reviewers = User.where(:id => reviewer_ids)

This grabs all the reviewers in a single database call.

Upvotes: 2

Raphael Petegrosso
Raphael Petegrosso

Reputation: 3870

Do the following to get the reviewers:

@reviewers = []
@invitations.each do |i|
  @reviewers << User.where("id = ?", i.reviewer_id )
end

The << adds elements to the array. And, before the iteration we create an array.

Upvotes: 1

Related Questions