Attempting to build query on the fly

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:

  1. #where with calculated values (e.g. where(field: value))
  2. #where with template (e.g. where("field1 > ? and field2 < ?", value1, value2))
  3. Progressive building of ARELs with conditional steps; for example:
    x = Model.where(condition)
    x = x.where(field1: field1_value) if field1_value.present?
    x = if group_by.present?
  1. Building complicated field lists with calculations programmatically; for example:
    suffix_list = %w(today yesterday this_week last_week)
    field_list = {|suffix| "sales_#{suffix} * currency_conversion as local_#{suffix}" }
    selects = "key1, key2, sum(field1) as field1, sum(field2) as field2, #{field_list.join(", ")}"
    x =

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.