[英]Rails 3 ActiveRecord query in an array
我有一個模型與另一個模型具有one_to_many關系:
user.area_ids = [1, 2, 3]
然后是另一種共享關系但一對一的模型。
listing.area_id = 1
如何查詢所有Area_id為1 2或3的列表。我希望做類似的事情...
Listing.where("area_id IN ?", user.area_ids)
但這是行不通的。
任何幫助,將不勝感激!
你太聰明了 Rails知道如何做where(field: [1,2,3])
就好了。
如果您where
提供常規key: value
,其中value是一個數組,它將為您建立where FIELD in (a,b,c)
的where FIELD in (a,b,c)
。
只需使用
Listing.where(area_id: user.area_ids) # select ... where area_id in (1,2,3)
您忘記了問號附近的括號:)嘗試以下操作:
Listing.where("area_id IN (?)", user.area_ids)
但是對我來說,更正確的方法是借助
class User
has_many :areas
has_many :listings, through: :areas
end
然后打電話
user.listings
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.