问题
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.
回答1:
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
回答2:
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
来源:https://stackoverflow.com/questions/11820182/dynamic-activerecord-finder-methods-chaining-based-on-params