1

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.

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

3 Comments

thanks! I am getting the following error, "Mysql2::Error: Operand should contain 1 column(s): SELECT users.* FROM users WHERE (id = 23,24,25)"
@Jay - You should do: @reviewers = User.where(:id => reviewer_ids)
No problem. Definitely go with what @mischa said re: where statement.
1

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.

1 Comment

thanks. I am using your solution. The error i am getting is now part of my post.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.