lundi 18 juillet 2016

Rails Query to return users belongs to any cities & not belong to any cities

I have Many to Many associations between two tables For Ex users & cities

users
id  name
1   Bob
2   Jon
3   Tom
4   Gary
5   Hary

cities
id     name 
1      London
2      New-york
3      Delhi

users_cities
id   user_id   city_id
1    1         2
2    2         1
3    3         1
4    3         2

I want two sql queirs

Query which accepts array of city_id and return all the users belongs to that cities. For Ex when city_id : [1, 2] then result should be O/P should be

   id  name
        1   Bob
        2   Jon
        3   Tom

Query which accepts array of city_id and return all the users which are not belongs to that cities. For Ex when city_id : [1, 2] then result should be O/P should be

    id  name
    4   Gary
    5   Hary

Note:- i am using

user.rb

has_and_belongs_to_many :cities

city.rb

has_and_belongs_to_many :users

Aucun commentaire:

Enregistrer un commentaire