Ruby on rails 3 Rails查询返回属于任何城市的用户&;不属于任何城市
我有两个表之间的Ruby on rails 3 Rails查询返回属于任何城市的用户&;不属于任何城市,ruby-on-rails-3,ruby-on-rails-4,activerecord,postgresql-9.1,has-and-belongs-to-many,Ruby On Rails 3,Ruby On Rails 4,Activerecord,Postgresql 9.1,Has And Belongs To Many,我有两个表之间的多对多关联:针对前用户和城市 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
多对多关联
:针对前用户和城市
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
我想要两个sql查询
接受城市id数组并返回属于该城市的所有用户的查询。
例如,当city_id:[1,2]时,结果应为
O/P应为
id name
1 Bob
2 Jon
3 Tom
接受城市id数组并返回不属于这些城市的所有用户的查询。
例如,当city_id:[1,2]时,结果应为
O/P应为
id name
4 Gary
5 Hary
注意:-我正在使用
user.rb
has_and_belongs_to_many :cities
has_and_belongs_to_many :users
city.rb
has_and_belongs_to_many :cities
has_and_belongs_to_many :users
基本上,您需要两个方法/作用域
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
如果您是Rails4.x,仍然需要一些简单的解决方案。有人在那里吗