mike0416
mike0416

Reputation: 461

Where clause rails -- using two Models

Not sure of the best way to do this - I have a where clause that I need to use two models In order to get list results for an autocomplete. I have a 'Membership' model that contains either a 'User' reference or a 'Member' reference (either the user_id is nil or the member_id is nil, but not both).

I need to list out both the User names AND the Member names for the current_user, plucking the user_id if not nil or the member_id, respectively.

I tried to add an && to the where clause but it doesn't seem to be working

 User.where(id:  current_user.memberships.pluck(&:user_id)) && Member.where(id: current_user.memberships.pluck(&:member_id)

How can I make this work and make it Railsy?

Upvotes: 1

Views: 152

Answers (1)

K M Rakibul Islam
K M Rakibul Islam

Reputation: 34318

This should give you what you want:

current_memberships = current_user.memberships
user_names = User.where('users.id in ?', current_memberships.pluck(:user_id).compact.uniq)
                 .select('users.name')
                 .map(&:name)
member_names = Member.where('members.id in ?', current_memberships.pluck(:member_id).compact.uniq)
                     .select('members.name')
                     .map(&:name)

# concat the array of user names and member names
user_names + member_names

Upvotes: 1

Related Questions