Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic ActiveRecord finder methods chaining based on params

Im new to rails and I want to make a select query based on diffrent GET params (filtering and sorting). Can I some how add conditions to find in the code?

For example:

if params[:ratings] 
  Movie.where(:rating => params[:ratings].keys)
end

and then add ordering and other where conditions. How can I achive this? Maybe there is a better way to dybamicly modify select query (without making SQL string). Thanks.

like image 846
Bartosz Rychlicki Avatar asked Jun 30 '26 00:06

Bartosz Rychlicki


2 Answers

The where, order, ... methods return ActiveRecord::Relation objects so you can keep calling more query methods:

query = Movie
if(params[:ratings])
  query = query.where(:rating => params[:ratings].keys)
end
if(params[:some_order_param])
  query = query.order(params[:some_order_param])
end
# Keep adding more 'where', 'order', 'group', ... methods as needed ...
results = query.all
like image 174
mu is too short Avatar answered Jul 02 '26 00:07

mu is too short


I'd actually recommend the has_scope gem for this type of behavior. It allows you to define scopes and class methods on your models and automatically use them for filtering, ordering, etc in the controllers.

Here's a small example from the docs, but there's a lot you can do with it:

class Graduation < ActiveRecord::Base
  scope :featured, where(:featured => true)
end

class GraduationsController < ApplicationController
  has_scope :featured, :type => :boolean
end
like image 37
Peter Brown Avatar answered Jul 01 '26 22:07

Peter Brown