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

若如初见. 提交于 2019-12-13 15:55:57

问题


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
5    4         3

I want two sql queries

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 who do not belong to those 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

回答1:


Basically you need two methods/scopes

class User < ActiveRecord::Base
  has_and_belongs_to_many :cities

  scope :by_cities, ->(city_ids) {includes(:cities).where(cities: {id: city_ids}).distinct}

  # There are several ways to do that
  # 1. That will return all not associated records but that we won't need
  # In this scenario, You need OR condition like city_ids OR NULL 
  # This will return => ["Hary"] 
  scope :not_by_cities, -> {includes(:cities).where(cities: {id: nil})}

  # 2. Need to create a scope in City model
  # scope :city_ids, -> all.pluck(:id) 
  # This will return => ["Gary", "Hary"] 
  scope :not_by_cities, -> {includes(:cities).where(cities: {id: [City.city_ids - city_ids, nil]})}

  # 3. If you are on Rails 5, It is much more easier
  # This will return => ["Gary", "Hary"] 
  scope :not_by_cities, -> {includes(:cities).where.not(cities: {id: city_ids}).where(cities: {id: nil})} 
end

For Option 2

class City < ActiveRecord::Base
    has_and_belongs_to_many :cities
    scope :city_ids, -> {all.pluck(:id)}
 end

Result:

>> User.by_cities([1,2]).pluck(:name)
=> ["Bob", "Jon", "Tom"]

>> User.not_by_cities.pluck(:name)
=> ["Gary", "Hary"] 

If You are Rails 4.x and still want some easy solution. Use anyone of there

  • Squeel
  • ActiverecordAnyOf
  • SmartTuple
  • Arel.

Hope this will help you.



来源:https://stackoverflow.com/questions/38439804/rails-query-to-return-users-belongs-to-any-cities-not-belong-to-any-cities

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!