【问题标题】:How to write request sql with symbol id如何编写带有符号 id 的请求 sql
【发布时间】:2015-11-28 03:21:15
【问题描述】:

我想在表 users 中找到一个用户,ID 如下:

<%= @user = User.find_by_sql("SELECT users . * FROM users WHERE id = [:id] ")%>

但我有一个例外:

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 '[:id]' at line 1: SELECT users . * FROM users WHERE id = [:id]

【问题讨论】:

  • 可能你在语法中放错了“”

标签: mysql sql ruby-on-rails ruby-on-rails-4 ruby-on-rails-4.2


【解决方案1】:

documentation

find_by_sql(sql, binds = [])

使用数组中的绑定包装查询:

=> User.find_by_sql(["select users.email from users where email = :q and first_name = :a", {q: 'foo', a: 'bar'}])

【讨论】:

  • 返回同样的错误:Mysql2::Error: You have an error in your SQL syntax;检查与您的 MySQL 服务器版本相对应的手册,以在第 1 行的 ':q' 附近使用正确的语法: SELECT users 。 * FROM users WHERE id = :q
  • 它应该是User.find_by_sql(["SELECT users .* FROM users WHERE id = :q", {q: 1}]) 第二个参数是一个哈希{ q: 'user_id' } 例如{ q: 1 }
  • 没关系,但我想检索符号中的 id :id
  • 我想检索符号 :id 中的 id 你是什么意思?
【解决方案2】:

试试这个

<%= @user = User.find_by_sql("SELECT users . * FROM users WHERE id = "[:id] 
)%>

【讨论】:

  • 返回:没有将 Symbol 隐式转换为 Integer
  • 将 [:id] 替换为 [:id].to_i
  • 再次返回:没有将 Symbol 隐式转换为 Integer
  • 符号id的数据类型是什么??
猜你喜欢
  • 1970-01-01
  • 2020-06-02
  • 2015-12-18
  • 1970-01-01
  • 1970-01-01
  • 2021-12-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多