开发者

Rails 3 noob - difficulty populating an array

UPDATED WITH SOLUTION FROM BELOW PRODUCE开发者_StackOverflow中文版S 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.


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜