简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM