Question

I'm writing a module for ActiveRecord models. In short it's a method that can call a series of where, join and order statements. The statements are not known at the time of writing so it is not possible to use scopes. So far it works well but there is one point I'd like to improve.

Here is my method:

def filter
  rel = respond_to?(:filter_scope) ? filter_scope : where(1)
  # Do other stuffs with `rel`
  # ...
  rel
end

It first call filter_scope if it is defined, or it obtain an ActiveRecord::Relation from the target model. To do so I use where(1) to force the model to return a relation object. This works well whenever I call filter directly on the model (User.filter) or on a relation (User.order(:name).filter, User.my_scope.filter.order(:age) etc...)

But using where(1) fells a bit dirty. In Rails 3 I would be using all instead but it's depreciated in Rails 4. Any idea on how to improve this?

Thanks in advance


Note: I cannot substitute where(1) by self because there is a possibility that self would be returned from filter and User.filter would be a class, therefore not usable as a query object.

Was it helpful?

Solution

In Rails 3 I would be using all instead but it's depreciated in Rails 4.

I don't think all is depreciated, it used to return an Array (rails 3) and now returns an ActiveRecord::Relation so you should be able to use it for chaining queries.

see http://api.rubyonrails.org/classes/ActiveRecord/Scoping/Named/ClassMethods.html#method-i-all

Returns an ActiveRecord::Relation scope object.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top