2

I have an application where I want to migrate from MetaWhere to Squeel in preparation for an upgrade to Rails 3.1.

This has been mostly a simple process but I have one case that causes me a bit of problems. The problem is that I have both the field and the value specified as variables. In my MetaWhere queries I could simply create symbols out of the field names and then use that in the query but Squeel does not use symbols but instead relies on instance_eval and I cannot figure out how to create a similar query using that...

An illustration of the original query could be:

Article.where("#{field_name}".to_sym.matches => '%' + field_value + '%')

How do I create a similar query in Squeel?

I know I can specify that I want to use the legacy symbol functionality but I would rather fully convert to the new syntax.

HakonB
  • 6,977
  • 1
  • 26
  • 27

1 Answers1

1

This works:

Article.where{article.send(field_name) =~ '%' + field_value + '%'}

The lowercase 'article' being the table name.

the-undefined
  • 753
  • 1
  • 6
  • 18
  • Brilliant. It needed curly braces instead of parentheses but other than that it works for me. Now I can remove some of that ugly SQL code :-) – HakonB Nov 08 '11 at 21:50
  • Excellent! I replaced the parentheses with curly braces as you say. :-) – the-undefined Nov 09 '11 at 17:06
  • it's not clear to me what "article" is, can please expand? a "table name" makes no sense to me, the more when in Rails they are always plural. – tokland Nov 15 '11 at 15:31
  • The plural part is just a convention and can be overriden. Say you have a customer who have a name which you for some reason want to filter on using the above syntax then the following would work Customer.where { customers.send(:name) =~ "%#{name_to_search_for}%" }. Does that make more sense? – HakonB Nov 17 '11 at 08:50