I have a model with a one_to_many relationship to another model such that:
user.area_ids = [1, 2, 3]
And then another model that shares the relationship but is a one to one.
listing.area_id = 1
How do I query for all the listings that are either area_id of 1 2 or 3. I am hoping to do something like...
Listing.where("area_id IN ?", user.area_ids)
But that doesn't work.
Any help would be appreciated!
You're being too clever. Rails understands how to do where(field: [1,2,3])
just fine.
If you give where
a regular key: value
where the value is an array, it will build the where FIELD in (a,b,c)
for you.
Just use
Listing.where(area_id: user.area_ids) # select ... where area_id in (1,2,3)
You forgot braces around question mark :) try this:
Listing.where("area_id IN (?)", user.area_ids)
But as for me, more proper way is to make it cleaner with a help of
class User
has_many :areas
has_many :listings, through: :areas
end
and then just call
user.listings
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.