Reputation: 139
User has many Relationships
In my relationships table i have a field :referee containing a user_id for each record. Each record also has user_id foreign key
I want to find the records that have current_user.id in the :referee field and select user_id from the foreign key field for each one.
refs = Relationship.where(:referee => current_user.id).select("user_id").all
This results in an array like this,
[#<Relationship user_id: 16>, #<Relationship user_id: 17>]
I now want to find User attributes for each of the ids in the array, I've tried but so far failed, for example:
User.where(:id => @refs_user_id).each do |user|
user.name
end
Did some reading/watching on active record advanced queries, scopes etc but can't quite seem to grasp what's required here. Any suggestions would be much appreciated, thanks!
Upvotes: 0
Views: 2491
Reputation: 42865
You can just pass an array of ids to ActiveRecord
User.find([1,2,3,4,5,6])
And if you just want to get the ids:
User.find(:all, :conditions => 'id IN (?)',[1,2,3,4,5,6], :select => 'id')
That will only return the ids.
Upvotes: 1
Reputation: 124419
You can select just the user_id
components like this:
User.where(:id => @refs_user_id.map(&:user_id)).each do |user|
user.name
end
Upvotes: 0