user938363
user938363

Reputation: 10368

How to query with string variable in rails 3.2.12?

We would like to store both rails query string and table name in db and retrieve them for execution at run time. Here is the scenario:

Retrieve active customer records from customers table. Let's say we have 2 variable defined as:

table_name = 'Customer'
query_string = ':active => true'

In rails, the query could be:

records = Customer.where(:active => true)

Now with table name and query string stored in variables table_name and query_string, is it possible to assemble a query string with 2 variables like:

 records = table_name.where(query_string) ?

Thanks for the help.

Upvotes: 0

Views: 323

Answers (2)

user938363
user938363

Reputation: 10368

The definition of instance_eval is: Evaluates a string containing Ruby source code, or the given block, within the context of the receiver (obj).

Another way to eval a query string is to include where in the string, like:

table_name = 'Customer'
query_string = 'where(:active => true)'

Then the record could be retrieved by:

records = table_name.constantize.instance_eval(query_string)

By putting where into the string, we can use the full power of instance_eval instead of just returning the source code to where as in the question above.

Upvotes: 1

PinnyM
PinnyM

Reputation: 35531

You could do this, but it's not generally recommended to evaluate a string as a hash. Also, table_name is an unfortunate name for the variable, because you actually are storing the class name (table would be 'customers'). In any event, what you are missing is the eval of these strings:

records = class_name.constantize.where(instance_eval(query_string))

Note that running instance_eval on a user-inputted string can be disasterous for security and the well-being of your application. Use with care, and stick to building an actual hash.

Upvotes: 2

Related Questions