ActiveRecord的动态查找方法链接基于PARAMS [英] Dynamic ActiveRecord finder methods chaining based on params
本文介绍了ActiveRecord的动态查找方法链接基于PARAMS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
林新轨道,我想根据不同势GET参数(筛选和排序)做出选择查询。可我一些如何添加条件来查找code?
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?
例如:
if params[:ratings]
Movie.where(:rating => params[:ratings].keys)
end
然后添加顺序等有条件的地方。我怎样才能achive呢?也许有更好的方法来dybamicly修改选择查询(未做SQL字符串)。 谢谢你。
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.
推荐答案
在其中,
,序
,.. 。方法返回的ActiveRecord ::关联对象,这样你就可以不停的叫唤更多的查询方法:
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
这篇关于ActiveRecord的动态查找方法链接基于PARAMS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文