has_many上的范围,:通过与id数组的关系

时间:2016-03-01 05:18:37

标签: ruby-on-rails ruby

我有以下关联:

#models/contact.rb
class Contact < ActiveRecord::Base
  has_many :relationships
  has_many :locations, through :relationships
end

#models/relationship.rb
class Relationship < ActiveRecord::Base
  belongs_to :contact
  belongs_to :location
end

#models/location.rb
class Location < ActiveRecord::Base
  has_many :relationships
  has_many :contacts, through: :relationships
end

我想要做的是创建一个范围,找到与contacts ID数组关联的所有location

我试过这个范围,但它没有用。它正确连接表,但我传入的数组似乎造成了一些麻烦。我在where子句中的语法似乎有问题。

#models/Contact.rb
class Contact < ActiveRecord::Base
  ...
  scope :by_locations, ->(ids_ary){joins(relationships: :location).where("locations.id IN ?", ids_ary)}
end

2 个答案:

答案 0 :(得分:1)

除了其他答案之外,您还可以重写查询以改为使用哈希:

scope :by_locations, ->(ids_ary) { joins(relationships: :location).where("locations.id" => ids_ary) }

答案 1 :(得分:0)

需要在问号周围添加括号:

scope :by_locations, ->(ids_ary){joins(relationships: :location).where("locations.id IN (?)", ids_ary)}