活动记录查询select_all,准备好的语句

时间:2013-07-11 16:16:14

标签: ruby-on-rails ruby-on-rails-3 activerecord ruby-on-rails-3.1 ruby-on-rails-3.2

我试图编写如下的预备语句:

@fofs = FileOrFolder.connection.select_all("select * from newtestdocB.file_or_folders where name like","%#{params[:search]}%")

原来是mysql控制台上的错误查询。不将变量%#{params [:search]}%value用于查询

请更正我的查询...

控制台消息:

Parameters: {"search"=>"do", "cluster_id"=>"2", "datasetid"=>"1", "id"=>"1"}
  %do% (0.2ms)  select * from newtestdocB.file_or_folders where name like

ActiveRecord::StatementInvalid (Mysql2::Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 1: select * from newtestdocB.file_or_folders where name like):

1 个答案:

答案 0 :(得分:0)

<强> Try a placeholder ?

“select * from newtestdocB.file_or_folders where name like?”,“%#{params [:search]}%”

请参阅上述声明中的问号,该问号将由逗号后面的参数填写。

如果以上语句不起作用,这必须有效,使用“+”连接,注意“喜欢”旁边的空格

sql = "select * from newtestdocB.file_or_folders where name like <<space>>" + "%#{params[:search]}%"

FileOrFolder.connection.select_all(sql)