Search code examples
ruby-on-railsactiverecord

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


I have a class method on User, that returns applies a complicated select / join / order / limit to User, and returns the relation. It also applies a where(:admin => true) clause. Is it possible to remove this one particular where statement, if I have that relation object with me?

Something like

User.complex_stuff.without_where(:admin => true)

Solution

  • 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.