我有以下关联:
#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
答案 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)}