Remove a 'where' clause from an ActiveRecord::Relation

I know this is an old question, but since rails 4 now you can do this

User.complex_stuff.unscope(where: :admin)

This will remove the where admin part of the query, if you want to unscope the whole where part unconditinoally

User.complex_stuff.unscope(:where)

ps: thanks to @Samuel for pointing out my mistake


I haven't found a way to do this. The best solution is probably to restructure your existing complex_stuff method.

First, create a new method complex_stuff_without_admin that does everything complex_stuff does except for adding the where(:admin => true). Then rewrite the complex_stuff method to call User.complex_stuff_without_admin.where(:admin => true).

Basically, just approach it from the opposite side. Add where needed, rather than taking away where not needed.


You could do something like this (where_values holds each where query; you'd have to tweak the SQL to match the exact output of :admin => true on your system). Keep in mind this will only work if you haven't actually executed the query yet (i.e. you haven't called .all on it, or used its results in a view):

@users = User.complex_stuff
@users.where_values.delete_if { |query| query.to_sql == "\"users\".\"admin\" = 't'" }

However, I'd strongly recommend using Emily's answer of restructuring the complex_stuff method instead.