Im attempting to build a query around a model on the fly. But it seems like i’m just assigning my instance variable just a string it cannot executed. Lol.
Any suggestions?
Im attempting to build a query around a model on the fly. But it seems like i’m just assigning my instance variable just a string it cannot executed. Lol.
Any suggestions?
Ok i figured it out… use eval() on the string.
Now i got to figure out how to resque from errors.
It would be great if you could share an example of what you are trying to achieve as I’m afraid eval
sounds like the least preferable option for that
Rails has some very good facilities for building queries on the fly; eval() is not one of them. Here are some of them:
where(field: value)
)where("field1 > ? and field2 < ?", value1, value2)
) x = Model.where(condition)
x = x.where(field1: field1_value) if field1_value.present?
x = x.group(group_by) if group_by.present?
suffix_list = %w(today yesterday this_week last_week)
field_list = suffix_list.map {|suffix| "sales_#{suffix} * currency_conversion as local_#{suffix}" }
selects = "key1, key2, sum(field1) as field1, sum(field2) as field2, #{field_list.join(", ")}"
x = x.select(selects)
There are more, but this is a good list to start with. Ruby and Rails are both designed with the idea of mixing features together that might not obviously be related in consistent, unsurprising ways, yielding creative but predictable results.