swapnilpatil24
swapnilpatil24

Reputation: 41

Rails where LIKE pass dynamic attribute with there values

I have search query and there I need to pass dynamic search attribute and values. Following query I am passing all field but those are not dynamic means Some time only first_name will be in search or some time first_name and last_name or some time first_name with age.

How the best way to pass those attributes and values as per found in search method.

Product.where(
  'first_name like ? OR last_name like ? OR age BETWEEN ? AND ?',
  params[:first_nm],
  params[:last_nm],
  params[:age_start],
  params[:age_end]
)

Upvotes: 0

Views: 444

Answers (3)

swapnilpatil24
swapnilpatil24

Reputation: 41

Thanks guys for inputs, Following solution worked for me. I think its pretty easy

params_hash = {}
if first_name
  where_str = 'first_name Ilike :ft_nm'
  params_hash[:ft_nm] = "swapnil"
end

if last_name
  where_str += 'last_name Ilike :lt_nm'
  params_hash[:lt_nm] = "patil"
end 

Product.where(where_str, params_hash)

Upvotes: 1

codenamev
codenamev

Reputation: 2208

If you can, I would update your form to submit the params to reflect the columns to search on. Then you can make this a bit easier with a scope:

ALLOWED_SEARCH_TERMS = %i(first_name last_name).freeze

scope :search, ->(terms) {
  result = all
  terms.slice(*ALLOWED_SEARCH_TERMS).each { |term, value| result = result.where(:"#{term}" => value) }
  result = result.where("age BETWEEN :age_start AND :age_end", terms.slice(:age_start, :age_end)) if terms.key?(:age_start) && terms.key?(:age_end)
  result
}

Then in your controller you can:

Product.search(params)

Upvotes: 0

Walid Da.
Walid Da.

Reputation: 948

This logic could help

level_one_result = Product.where('first_name like ? OR last_name like ?',"%#{params[:first_nm]}%", "%#{params[: last_nm]}%")
if (params[:age_end].to_i > 0 or params[:age_end].to_i > 0)
  if params[:age_start].to_i > 0 and params[:age_end].to_i > 0
     result = level_one_result.where('age >= ? AND age <= ?',params[:age_start].to_i,params[:age_end].to_i)
  elsif params[:age_end].to_i > 0
     result = level_one_result.where('age <= ?',params[:age_end].to_i)
  else
     result = level_one_result.where('age >= ?',params[:age_start].to_i)
  end
else
  result = level_one_result
end

Upvotes: 0

Related Questions