简体   繁体   中英

Complex left outer join query

I have a Rails app with a complex query I can't seem to solve. I have 2 tables, clubs and selections. Table clubs is just like this:

id,name
1,A
2,B
3,C
4,D

Table selections contains the selected clubs from table clubs by all the users:

id,club_id,user_id
1,1,1
2,1,2
3,2,3
4,3,1
5,3,3

Now I want a select box with all items from table clubs without the elements already chosen by the current user (he can't chose the same club twice). So in the case of user 1, it should only show clubs B and D, because he already has chosen A and C.

So I created this as a scope in the model:

  scope :selectable, ->(current_user) {
    joins('LEFT OUTER JOIN selections ON selections.club_id = clubs.id').
    where('selections.id IS NULL OR selections.user_id != ?', current_user.id).
    group('clubs.id')
  }

This works fine when there is only one user making selections, but if more users chose the same club as the current user, these clubs still show up. What can I improve to show the correct clubs?

I found a solution which seems to work, but I don't know if it is the most elegant one:

  scope :selectable, ->(current_user) {
    joins('LEFT OUTER JOIN selections ON selections.club_id = clubs.id').
    where('selections.id IS NULL OR selections.user_id != ?', current_user.id).
    where('clubs.id NOT IN (?)', current_user.clubs).
    group('clubs.id')
  }

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