I'm writing a controller method which may optionally modify a query (eg, by ordering it).
Coming from a django background, I would normally do something like:
def method(**kwargs):
data = Model.all() # in django, this is a QuerySet
# chain the order if required
if 'order' in kwargs:
data = data.order_by(kwargs['order'])
I tried to do the same in ruby:
def method
@data = Model.all # in rails, this is an *array*
if params.has_key? :sort then
@data = @data.order(params[:sort])
# also do other things, which is why this isn't a one-liner
end
However, .all
returns an Array
, so that is not possible.
I've had a look through the Active Record Where Chain Reference, but I can't find anything which will return a chainable object representing the whole query. Is this possible?
(The requirement I'm after is that if :sort
is not a param, @data
is still usable anywhere where a WhereChain
object is expected.)