Dynamic ActiveRecord finder methods chaining based on params

[亡魂溺海] 提交于 2020-01-01 14:35:21

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!