Tuesday 15 September 2015

sql - Complex left outer join query -


I have a rail app with a complex query that I can not solve. I have 2 tables, clubs and select tableclubs like this:

  id, name1, a2, b3, c4, d   < P> Selected table includes selected clubs by all 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 the items of the table club without the elements already selected by the existing users (it should not be selected twice for the same club can). Therefore, in the case of User 1, only Club B and D should be shown, because it has already selected A and C.

So I created it as a scope in the model:

  scope: selection, -> (Current_USUG) {Gets ('Selected options in the selection: .club_id = clubs.id') where ('selections.id is tap or selection. User_id! =?', Current_user.id). The group ('clubs.id')}   

This works fine only when only one user is selecting, but if more users choose the same club as the current user If selected, these clubs are still shown. What can I improve to show the right club?

I found a solution that seems to work, but I do not know it's the most beautiful :

  scope: selection, -> & gt; (Current_useor) {(Select the additional options selected in the selection .club_id = clubs.id '). Where ('selections.id is tap or selection. User_id! =?', Current_user.id). Where ('clubs.id (?)', Current_user.clubs). Group ('clubs.id')}    

No comments:

Post a Comment