0

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?

4

1 回答 1

1

我找到了一个似乎可行的解决方案,但我不知道它是否是最优雅的解决方案:

  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')
  }
于 2013-06-20T18:28:51.490 回答