0

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!

2
  • Try: user.area_ids.join(',') Commented Oct 25, 2014 at 20:33
  • 1
    @Brian No, that's a very ugly solution. Rails understands how to do where(field: [1,2,3]) just fine. Commented Oct 25, 2014 at 20:58

2 Answers 2

3

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)
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks! This worked for me as did the other answer. Just for learning's sake -- why should I avoid building query manually. Security issue?
No, because there is absolutely no need to. Rails can do it, so let Rails do it. The database backend you're using now might use where in (...), but you might decide tomorrow that you want to use a different database, and if you let Rails do what it's good at, your code won't have to change at all. If you've built a bunch of queries by hand, it would be a headache.
Thanks for the quick response. What if I want to query the other way around from the User side? I want all the users that have 1 in the user.area_ids (the listing.area_id)?
2

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.