Search code examples
ruby-on-railsactiverecordconditional-statementsbackslash

ActiveRecord find Option with :conditions : how to replace backslash \ with double backslash \\ if :conditions is a string instead of a hash


I have the problem that rails 2.X do not replaces a backslash (\) with two backslashes (\\) , if :conditions is a string. It only replaces it with two backslashes, when you have a hash for :conditions e.g. following:

Parameter.find(:first, :conditions =>{ :key1 => var.to_s })

But in my case :conditions is not a hash, but a string. How it can replaces the "\" automatically in a correct way with "\\", if I do not want to use gsub-function?

My Problem is, that my :conditions is a very long string, which contains a backslash. And because of different reasons ( include option , ...). I cannot use a hash for it. The following find-thing do not replaces "\" automatically with "\\" .

var =  "test\test"

Parameter.find(:first, :conditions => ' key1 = \'' + var.to_s + '\''  )

I would be thankful for any helpful hint, thanx.


Solution

  • Use array conditions:

    Parameter.first :conditions => ["key1 = ?", var]
    

    See http://guides.rubyonrails.org/active_record_querying.html#array-conditions for more info.