One or More Params in Model Find Conditions with Ruby on Rails

Ruby on Rails search with multiple parameters

Check out the has_scope gem: https://github.com/plataformatec/has_scope

It really simplifies a lot of this:

class Graduation < ActiveRecord::Base
scope :featured, -> { where(:featured => true) }
scope :by_degree, -> degree { where(:degree => degree) }
scope :by_period, -> started_at, ended_at { where("started_at = ? AND ended_at = ?", started_at, ended_at) }
end

class GraduationsController < ApplicationController
has_scope :featured, :type => :boolean
has_scope :by_degree
has_scope :by_period, :using => [:started_at, :ended_at], :type => :hash

def index
@graduations = apply_scopes(Graduation).all
end
end

Thats it from the controller side

Model.where() with multiple params with check if they are present in rails

You could add where statements incrementally when each parameter is present:

@xyz = Seeker.scoped
@xyz = @xyz.where(id: params[:id]) if params[:id].present?
@xyz = @zyx.where(mobile_number: params[:mobile_number]) if params[:mobile_number].present?

A cleaner approach could be to move that logic to some scope or class method in the Seeker model maybe.

Rails Search with multiple Conditions

You could just create an initial query and chain on it while you go, from what I can see the order part is common and always present, so use it as the base query

@event_results = Event.order(event_date: :asc)
@event_results = @event_results.where('event_results.name LIKE ?', "%#{params[:query]}%") if params[:query]
@event_results = @event_results.joins(:host).where(host_type: params[:host_type]) if proper_condition
@event_results = @event_results.more_methods if more_conditions
#etc

@event_results #the return

By default ruby will return the last statement, so you don't need to use return, unless the last statement returns something like true/false then you should just add a new line with the variable @event_results

NOTE: never use input directly from params into your query, you're allowing people to inject sql to your code, use the substitution
method so that ActiveRecord would sanitize the input for you.

Bad:

where("name LIKE '%#{params[:query]}%'")

Good:

where('name LIKE ?', "%#{params[:query]}%")

Use the same parameters many times in a find conditions: hash

I would use named_scope. In model add:

named_scope :valid, 
:conditions =>
["valid_from <= ? and valid_to >= ?", Date.today, Date.today]

And then in your controller you can call:

@mymodels = Mymodel.valid

I think that focusing on reducing two calls to Date.today to only one call is wasting of time. It won't make your application faster or using less memory.

Rails ActiveRecord: Multiple conditions in find

Rails 2

find(:all, :conditions => ['name LIKE ?', "%#{search}%"], ['active', 1]) isn't the proper syntax for passing hashes to a method. You can leave the curly braces off of a hash if it is the last argument to a method, but in this case you are passing an array as the last argument.

Use the following instead:

find(:all, :conditions => ["name LIKE ? AND active = ?", "%#{search}%", 1])

or

params = {:search => "%#{search}%", :active => 1}
find(:all, :conditions => ["name LIKE :search AND active = :active", params])

Rails 3 and 4

You would probably want to do something more like the following for recent Rails versions:

 scope :active, -> { where(active: true) }
scope :name_like, ->(search) { where("name LIKE ?", "%#{search}%") }

And then you'd call it like this:

YourModel.active.name_like("Bunnies")

That allows you to reuse those specific queries in different combinations throughout the application. It also makes the code retrieving the data super easy to read.

If you don't like the scope syntax, you can also define these as class methods:

def self.active
where(active: true)
end

def self.name_like(search)
where("name LIKE ?", "%#{search}%")
end

You can also chain scopes on the fly. That will allow you to start building a chain of relation objects and then choose to include others based on conditions. Here's what it could look like when applied to the original question to achieve the same results:

results = active
results = results.name_like(search) if search.present?

Search after multiple parameters, Ruby on Rails

Model:

class Journey < ActiveRecord::Base
def self.search(search_from, search_to)
self.where("from_place LIKE ? and to_place LIKE ?", "%#{search_from}%", "%#{search_to}%")
end
end

Controller:

class JourneysController < ApplicationController

def index
if params[:search_from] and params[:search_to]
@journeys = search
else
@journeys = Journey.all.order('created_at DESC')
end
end

def search
@journeys = Journey.search(params[:search_from], params[:search_to])
end
end

Ruby Gem ActiveRecord find method with multiple conditions

Use where:

Like.where('user_id = ? AND post_id = ?', params[:user_id], params[:post_id])

or

Like.where('user_id = :user_id AND post_id = :post_id', params)

Is important to keep in mind that the paremeters of the where need to be converted to the expected type for example params[:post_id].to_i

Where condition to find record by mutliple params in assocaited model?

where returns an array records but you are looking for a single record only. You can use find_by which returns the first record matching the conditions (or nil, if none was found):

@product = Product.find_by(
style_id: @user_product.style_id,
size: @user_product.size,
color: @user_product.color,
country: @user_product.country
)
if @product
@user_product.product_id = @product.id
else
# add an error if the product is not found,
# or do something else
end


Related Topics



Leave a reply



Submit