简体   繁体   中英

Rails Active Record query with multiple optional params

What would be the optimised way to create an ActiveRecord query in a Rails 4.1 application controller which can 0 to 4 optional query params, in absence of which I must return all the items: -

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

Any help is appreciated.

Create scopes on the model, then have a class method on the model to filter based on the params passed.

Create scopes on Task model - some examples:

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

Create class method on Task model to apply scopes - returns all tasks if no params are present

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

This can then be called from the controller

@tasks = Task.filter(params)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM