我有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
它有效,但它非常难看。有没有更好的方法来实现这一目标?理想情况下是一行查询。
更新
现在我有了
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))
返回'SA','VIC','VIC'
但整个查询将生成
SELECT DISTINCT "centres".* FROM "centres" WHERE (centres.state_id IN (NULL,NULL,NULL))
答案 0 :(得分:0)
如果是,用户是否也有state_id列然后尝试这个, User.joins(“LEFT OUTER JOIN用户ON users.state_id = centers.state_id”) 其他 尝试User.joins(:center)
答案 1 :(得分:0)
解决。
.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)