Rails通过sql转义冒号找到

时间:2012-04-23 17:39:55

标签: ruby-on-rails

我正在尝试在模型上运行SQL查询,其值为冒号':'。

类似的东西:

Model.find_by_sql([SELECT * FROM table WHERE field1 = ? AND field2 ='some:value'], params)

这会导致以下错误:

  

的ActiveRecord :: PreparedStatementInvalid

任何人都知道如何正确地将冒号':'转移到上面的field2的值文本中?

2 个答案:

答案 0 :(得分:2)

使用where,它会缩短代码:

Model.where("field1 = ? AND field2 ='some:value']", params)

具体例子:

1.9.3-head :024 > Tag.where('created_at <= ? and name = "some:value"', Time.now)
  Tag Load (1.6ms)  SELECT "tags".* FROM "tags" WHERE (created_at <= '2012-04-23 18:06:54.967319' and name = "some:value")
 => [#<Tag id: 2419, name: "some:value", created_at: "2012-04-23 18:06:35", updated_at: "2012-04-23 18:06:35">] 

答案 1 :(得分:1)

关于价值的

gsub!(':','\\:\\')应该有效。