使用数组中的条件查询
Query using condition within an array
我有 2 个模型,用户和中心,它们之间存在多对多关系。
class User < ActiveRecord::Base
attr_accessible :name
has_and_belongs_to_many :centres
end
class Centre < ActiveRecord::Base
attr_accessible :name, :centre_id, :city_id, :state_id
has_and_belongs_to_many :users
end
现在我有一个拥有多个中心的用户,我想检索与该用户具有相同 "state_id" 的所有中心。
这就是我现在正在做的事情
state_id_array = []
user.centres.each do |centre|
state_id_array << centre.state_id
end
return Centre.where("state_id IN (?)", state_id_array).uniq
它可以工作,但是非常难看。有没有更好的方法来实现这一目标?理想情况下是一行查询。
UPDATE
现在我有
Centre.where('centres.state_id IN (?)', Centre.select('state_id').joins(:user).where('users.id=(?)', user))
子查询自己工作,但是当我尝试执行整个查询时,内部查询得到 NULL。
Centre.select('state_id').joins(:user).where('users.id=(?)', user)
将生成
SELECT state_id FROM "centres" INNER JOIN "centres_users" ON "centres_users"."centre_id" = "centres"."id" INNER JOIN "users" ON "users"."id" = "centres_users"."user_id" WHERE (users.id = (5))
其中 return 'SA', 'VIC', 'VIC'
但整个查询将生成
SELECT DISTINCT "centres".* FROM "centres" WHERE (centres.state_id IN (NULL,NULL,NULL))
用户是否也有 state_id 列,如果是,那么试试这个,
User.joins("LEFT OUTER JOIN users ON users.state_id = centers.state_id")
别的
试试 User.joins(:center)
已解决。
.select(:state_id)
将检索仅填充了 state_id 列的模型。要检索字段,请使用
.pluck(:state_id)
以下是我的最终查询
Centre.where('centres.state_id IN (?)', Centre.joins(:user).where('users.id=(?)', user).pluck('state_id').uniq)
我有 2 个模型,用户和中心,它们之间存在多对多关系。
class User < ActiveRecord::Base
attr_accessible :name
has_and_belongs_to_many :centres
end
class Centre < ActiveRecord::Base
attr_accessible :name, :centre_id, :city_id, :state_id
has_and_belongs_to_many :users
end
现在我有一个拥有多个中心的用户,我想检索与该用户具有相同 "state_id" 的所有中心。
这就是我现在正在做的事情
state_id_array = []
user.centres.each do |centre|
state_id_array << centre.state_id
end
return Centre.where("state_id IN (?)", state_id_array).uniq
它可以工作,但是非常难看。有没有更好的方法来实现这一目标?理想情况下是一行查询。
UPDATE
现在我有
Centre.where('centres.state_id IN (?)', Centre.select('state_id').joins(:user).where('users.id=(?)', user))
子查询自己工作,但是当我尝试执行整个查询时,内部查询得到 NULL。
Centre.select('state_id').joins(:user).where('users.id=(?)', user)
将生成
SELECT state_id FROM "centres" INNER JOIN "centres_users" ON "centres_users"."centre_id" = "centres"."id" INNER JOIN "users" ON "users"."id" = "centres_users"."user_id" WHERE (users.id = (5))
其中 return 'SA', 'VIC', 'VIC'
但整个查询将生成
SELECT DISTINCT "centres".* FROM "centres" WHERE (centres.state_id IN (NULL,NULL,NULL))
用户是否也有 state_id 列,如果是,那么试试这个, User.joins("LEFT OUTER JOIN users ON users.state_id = centers.state_id") 别的 试试 User.joins(:center)
已解决。
.select(:state_id)
将检索仅填充了 state_id 列的模型。要检索字段,请使用
.pluck(:state_id)
以下是我的最终查询
Centre.where('centres.state_id IN (?)', Centre.joins(:user).where('users.id=(?)', user).pluck('state_id').uniq)