Rails 3 ActiveRecord query using both SQL IN and SQL OR operators Rails 3 ActiveRecord query using both SQL IN and SQL OR operators ruby ruby

Rails 3 ActiveRecord query using both SQL IN and SQL OR operators


You don't need to use raw SQL, just provide the pattern as a string, and add named parameters:

Question.where('user_id in (:ids) or target in (:usernames)',                :ids => self.friends.ids, :usernames => self.friends.usernames)

Or positional parameters:

Question.where('user_id in (?) or target in (?)',                self.friends.ids, self.friends.usernames)

You can also use the excellent Squeel gem, as @erroric pointed out on his answer (the my { } block is only needed if you need access to self or instance variables):

Question.where { user_id.in(my { self.friends.ids }) |                 target.in(my { self.friends.usernames }) }


Though Rails 3 AR doesn't give you an or operator you can still achieve the same result without going all the way down to SQL and use Arel directly. By that I mean that you can do it like this:

t = Question.arel_tableQuestion.where(t[:user_id].in(self.friends.ids).or(t[:username].in(self.friends.usernames)))

Some might say it ain't so pretty, some might say it's pretty simply because it includes no SQL. Anyhow it most certainly could be prettier and there's a gem for it too: MetaWhere

For more info see this railscast: http://railscasts.com/episodes/215-advanced-queries-in-rails-3and MetaWhere site: http://metautonomo.us/projects/metawhere/

UPDATE: Later Ryan Bates has made another railscast about metawhere and metasearch: http://railscasts.com/episodes/251-metawhere-metasearchLater though Metawhere (and search) have become more or less legacy gems. I.e. they don't even work with Rails 3.1. The author felt they (Metawhere and search) needed drastic rewrite. So much that he actually went for a new gem all together. The successor of Metawhere is Squeel. Read more about the authors announcement here:http://erniemiller.org/2011/08/31/rails-3-1-and-the-future-of-metawhere-and-metasearch/and check out the project home page:http://erniemiller.org/projects/squeel/"Metasearch 2.0" is called Ransack and you can read something about it from here:http://erniemiller.org/2011/04/01/ransack-the-library-formerly-known-as-metasearch-2-0/


Alternatively, you could use Squeel. To my eyes, it is simpler. You can accomplish both the IN (>>) and OR (|) operations using the following syntax:

Question.where{(:user_id >> my{friends.id}) | (:target >> my{friends.usernames})}

I generally wrap my conditions in (...) to ensure the appropriate order of operation - both the INs happen before the OR.

The my{...} block executes methods from the self context as defined before the Squeel call - in this case Question. Inside of the Squeel block, self refers to a Squeel object and not the Question object (see the Squeel Readme for more). You get around this by using the my{...} wrapper to restore the original context.