Rails ActiveRecord find w/ conditions

Hey guys! First time posting so let see how this goes… got a question:

I’m trying to find a record in a table minus any leading / trailing
whitespaces.

This code will find the record but it wont return anything if the
value in the table’s column (named MyColumn) had any whitespaces at
the beginning or at the end of it:
found_record = MyTable.find(:first,:conditions => [ “MyColumn = ?”,
someValue ])

I tried this and it obviously didnt work:
found_record = MyTable.find(:first,:conditions => [ “MyColumn.strip =
?”, someValue ])

I dont wanna modify the data in the table, just find a match.
What can I do? Thanks!

On 4 Dec 2007, at 20:37, Nabeel Mr. wrote:

found_record = MyTable.find(:first,:conditions => [ “MyColumn = ?”,
someValue ])

I tried this and it obviously didnt work:
found_record = MyTable.find(:first,:conditions => [ “MyColumn.strip =
?”, someValue ])

At this point you’ve got 2 solutions:

  • at the point of saving the record, strip the whitespace. The whole
    problem goes away completely (that’s what I’d do).
  • drop down to some slightly rawer sql. Assuming your database has a
    function that removes trailing and leading whitespace (in mysql it’s
    TRIM) you can do something like
    MyTable.find(:first,:conditions => [ “TRIM(MyColumn) = ?”,someValue ])

Fred

The :conditions option gets plugged into a sql statement, so you can
use whatever facilities your database provides for that sort of
thing. In PostgreSQL, I’d do something like:

:conditions => [“trim(both ’ ’ from MyColumn) = ?”, someValue]

Peace,
Phillip

Thanks guys! The TRIM SQL statement worked like a charm :slight_smile:

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs