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.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With