我有两个模型User
和Service
。 User
的{{1}} has_and_belongs_to_many Services
同样适用于Services
:
class User < ActiveRecord::Base
has_and_belongs_to_many :services
end
class Service < ActiveRecord::Base
has_and_belongs_to_many :users
end
我需要找到提供所选服务的所有用户。类似的东西:
@users = User.where(:services_ids =&gt; [2,3,4])
答案 0 :(得分:1)
这应该有效:
User.join(:services).where(:services.id => [2,3,4]).uniq
答案 1 :(得分:0)
试试这个:
@users = Service.where(:id => [2,3,4])).map{|svc| svc.users}.uniq.flatten
或
@users = User.all(:include => :services, :conditions => ["services.id in ?", (2,3,4)])