Is it possible to have variable search conditions for key and value?

I am trying to pass both a field and a value in a find call:

@employee = Employee.find(:all,
              :conditions => [ '? = ?', params[:key], params[:value].to_i)

Output signal

SELECT * FROM `employees` WHERE ('is_manager' = 1)

This does not return any results, however, when I try to execute it directly in mysqsl using the same call without `` around is_manager, it works fine. How to convert the value of params [: key] to a character so that the resulting SQL query looks like this:

SELECT * FROM `employees` WHERE (is_manager = 1)

Thanks D

+3
source share
3 answers

You can use variable substitution for the column name instead of using binding values:

# make sure the key passed is a valid column
if Employee.columns_hash[params[:key]]
  Employee.all :conditions => [ "#{params[:key]} = ?", params[:value]]
end

You can also protect the solution by indicating that the passed column name belongs to a preselected collection:

if ["first_name", "last_name"].include? [params[:key]]
  Employee.all :conditions => [ "#{params[:key]} = ?", params[:value]]
end
+1
source

( , params [: key], , ,

params[:key].to_s.to_sym

2 :

  • : .

  • , , to_s to_sym, , wierd , :

    :"5"

+3

"string" .to_sym

+1
source

Source: https://habr.com/ru/post/1742126/


All Articles