Rails Active Record查询具有多个可选参数

时间:2017-10-05 19:32:26

标签: ruby-on-rails ruby-on-rails-4 activerecord rails-activerecord

在Rails 4.1应用程序控制器中创建ActiveRecord查询的优化方法是什么,可以使用0到4个可选查询参数,如果没有,我必须返回所有项目: -

i) GET /tasks -> returns all tasks

ii) GET /tasks?created=10347892 -> return tasks created after params[:created] timestamp

iii) GET /tasks?nearTo=0,0 -> return tasks near to 3 kms of params[:nearTo] geocoordinate

iv) GET range=range1 -> return tasks with range like 'range1' 

v) of course we need to support the following query GET /tasks?created=1034589&nearTo=0,0&range=range1

感谢任何帮助。

1 个答案:

答案 0 :(得分:2)

在模型上创建范围,然后在模型上有一个类方法,根据传递的参数进行过滤。

在任务模型上创建范围 - 一些示例:

scope :created_after, -> (time) { where("tasks.created_at > ?", time) }
scope :created_between, -> (start_time, end_time) { where("tasks.created_at >= ? AND tasks. created_at <= ?", start_time, end_time) }
scope :near_to, -> (x, y, miles) { near([x, y], miles) }
scope :range_like, -> (query) { where("tasks.range LIKE ?", query) }
scope :with_users, -> (user_ids) { where(tasks: {user_id: user_ids}) }
...
etc

在任务模型上创建类方法以应用范围 - 如果不存在参数,则返回所有任务

def self.filter(params)
  tasks = Task.all
  tasks = tasks.created_after(params[:created]) if params[:created].present?
  ...
  ...
  tasks = tasks.range_like(params[:range])      if params[:range].present?
  tasks = tasks.with_users(params[:user_ids])   if params[:user_ids].present?
  return tasks
end

然后可以从控制器

调用它
@tasks = Task.filter(params)