在rails 3中查询相关的has_many模型

时间:2012-06-04 23:49:20

标签: ruby-on-rails ruby-on-rails-3 activerecord

我有两个模型UserServiceUser的{​​{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])

2 个答案:

答案 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)])