Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)
like image 296
Dogbert Avatar asked Jun 13 '11 14:06

Dogbert


People also ask

How do you delete an ActiveRecord?

Deleting a row from a particular table or a record set from a table is pretty simple, from your console all you need to do is grab the record set by its Id then delete or destroy it.

What is ActiveRecord :: Base in rails?

ActiveRecord::Base indicates that the ActiveRecord class or module has a static inner class called Base that you're extending. Edit: as Mike points out, in this case ActiveRecord is a module... ActiveRecord is defined as a module in Rails, github.com/rails/rails/tree/master/activerecord/lib/…

What is an ActiveRecord relation object?

The Relation Class. Having queries return an ActiveRecord::Relation object allows us to chain queries together and this Relation class is at the heart of the new query syntax. Let's take a look at this class by searching through the ActiveRecord source code for a file called relation.

How do you use destroy in Ruby on Rails?

To create the controller action for the destroy-resource, we perform three substeps: (1) create an empty destroy-resource controller action, (2) add code to the action that retrieves the model object, and (3) add code to the action that destroys the model object and responds to the browser with an HTTP redirect.


2 Answers

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

like image 192
Mohammad AbuShady Avatar answered Sep 20 '22 17:09

Mohammad AbuShady


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.

like image 27
Emily Avatar answered Sep 18 '22 17:09

Emily