Rails Search with Optional Parameters

Ruby .where query with optional params

I would suggest that you add the conditions and then return 1 value at the end.

Example:

get do
notes = Note.where(user_id: current_user.id)

if params[:activity_id].present?
notes = notes.where(activity_id: params[:activity_id])
end

::Notes::DetailedSerializer.new(notes)
end

That way, you can add as many parameters as you want. You can also change the params[:activity_id] into a loop of params:

get do
notes = Note.where(user_id: current_user.id)

%i(activity_id).each do |param|
if params[param].present?
notes = notes.where(param => params[param])
end
end

::Notes::DetailedSerializer.new(notes)
end

so you can loop through whatever params you want

Rails - how to make query parameters optional in Model?

You can atrriubte these to nil

def self.filter(type =nil, min=nil, max=nil, start_at=nil, end_at=nil)
a = YourModel
a = a.where(type => min..max) if min.present? && max.present?
a = a.where(first_date: start_at..end_at) if start_at? && end_at.present?
a = a.order("#{type}#": :desc) if type.present?
a
end

Rails Active Record query with multiple optional params

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)

Query the database with Rails where method with optional parameters

You can add additional where clauses to your original query only if the optional parameters are present. The query won't be executed until you try to access the results of the query. For instance:

@budgets = Budget.where(marketplace_id: params[:marketplace_id], 
budget_year_id: params[:budget_year_id])

@budgets = @budgets.where(vendor: params[:vendor]) if params[:vendor]
@budgets = @budgets.where(details: params[:details]) if params[:details]

Optional where in Rails

You can pass the conditions to where in a hash syntax so just create a hash with all the conditions and pass it to where

conditions = {}
conditions[:status] = params[:status].present? ? params[:status] : 1
conditions[:parent_id] = nil if params[:status].blank?

@pages = Page.where(conditions).order(sort_column + ' ' + sort_direction)

rails search form with optional fields

Try like this:

def index
# All records by default
@guidelines = Guideline.where(1)
# Add `program` scope if a value is given
@guidelines = @guidelines.program(params[:program_code]) unless params[:program_code].blank?
# Add `investor` scope if a value is given
@guidelines = @guidelines.investor(params[:investor]) unless params[:investor].blank?
end

Note that each scope uses a unless something.blank? condition, which excludes the case when the parameter is an empty string

Best way to send() optional parameter in Rails

If you're using Ruby 2.2.0 or later you can call #itself on any object and get that object. So in your example you can do

def foo param_1, param_2 = :itself
object.send(param_1).send(param_2)
end

And it will be the same as

def foo param_1, param_2 = nil
thing = object.send(param_1)
if param_2
thing.send(param_2)
else
thing
end
end

I also second Surya's advice to always use #public_send instead.

Rails 3 Route with Multiple Optional Parameters

You can use the constraints with lambda to use multiple search options:

  search_options = %w(country state loc)
get('search/*path',:to => 'people#search', constraints: lambda do |request|
extra_params = request.params[:path].split('/').each_slice(2).to_h
request.params.merge! extra_params # if you want to add search options to params, you can also merge it with search hash
(extra_params.keys - search_options).empty?
end)

You can make a different lambda for more complex routes



Related Topics



Leave a reply



Submit