iosMessenger
iosMessenger

Reputation: 73

how to use dynamic variable for symbols in ruby where statements

I dont how to accomplish this problem.

I faced with this problem 3 times and each time I put it in my todo list but even tho I tried to find a solution I couldnt.

For examples,

I m trying to create a query with dynamic variables of this example;

User.search(first_name_start: 'K')

there are 3 arguments in this example;

1)first_name - My model attribute 2)start - Query type (start/end/cont ) 3)'3' - value

I was able to create dynamic ActiveRecord using static symbols but how am I suppose to make dynamic input

Thanks in advance

EDIT: ADDITIONAL INFORMATION

let me show you a some kind of pseudo-code

    varArray.each_with_index |x,index|

    queryString=varArray[i]+"_"+filterArray=[i] #lets say varArray[i], this will be first_name, an actual model attribute/a column in my db 
#and filterArray like /start/end/with a filter type
#and finally valArray a string value like  'geo' or 'paul'
User.where(queryString valArray[i]).result 

I tried to use send(variable) but that didnt help me either, so i dont how should i proceed,

Upvotes: 1

Views: 1434

Answers (1)

D-side
D-side

Reputation: 9495

This is one of a few cases where new fancy Ruby 1.9 syntax for defining hashes doesn't cut it. You have to use the traditional hashrocket (=>) that allows you to specify not only symbols, but any arbitrary values as hash keys:

column = "#{first_name}_size_#{query_type}".to_sym
User.where( column => value )

AFAIK, ActiveRecord is able to accept strings instead of symbols as column names, so you don't even need to call to_sym.

Upvotes: 2

Related Questions