首页 > 解决方案 > Rails 6 sqlite3中的更新/删除语法错误

问题描述

为什么 rails db 的行为与运行时 sql 不同?

使用 rvm 1.29.11 创建了一个新应用程序;导轨 6.1.1;红宝石 3​​.0.0p0; sqlite3 3.28.0。生成简单的脚手架导轨 gs 名称电话。迁移的数据库(rails db:migrate)。应用程序启动并运行。能够创建、更新和删除记录。但是,当我尝试运行使用 rails db 执行的命令时,出现以下错误:

app/controllers/stores_controller.rb:67:in `set_store'
  TRANSACTION (0.0ms)  begin transaction
  ↳ app/controllers/stores_controller.rb:44:in `block in update'
  Store Update (0.4ms)  UPDATE "stores" SET "phone" = ?, "updated_at" = ? WHERE "stores"."id" = ?  [["phone", "1234"], ["updated_at", "2021-01-10 21:39:51.295940"], ["id", 2]]
  ↳ app/controllers/stores_controller.rb:44:in `block in update'
  TRANSACTION (1.5ms)  commit transaction
  ↳ app/controllers/stores_controller.rb:44:in `block in update'
Redirected to http://0.0.0.0:3001/stores/2
Completed 302 Found in 9ms (ActiveRecord: 2.0ms | Allocations: 3248)

从轨道数据库

 rails db
SQLite version 3.28.0 2019-04-15 14:49:49
Enter ".help" for usage hints.
sqlite>  UPDATE "stores" SET "phone" = ?, "updated_at" = ? WHERE "stores"."id" = ?  [["phone", "1234"], ["updated_at", "2021-01-10 21:39:51.295940"], ["id", 2]];
Error: near "[["phone", "1234"]": syntax error
sqlite> .quit

为什么 rails db 的行为与运行时 sql 不同?我正在从开发日志复制/粘贴到 db:console 并添加终止“;”?

标签: ruby-on-railssqlite

解决方案


rails db不是 Rails 控制台,它是SQL 数据库的控制台。在这种情况下,SQLite 命令行。Ruby 和 Rails 命令在这里不起作用,只有 SQL 和 SQLite 命令。["phone", "1234"]是红宝石。

Rails 控制台是rails console或只是rails c. 这接受 Ruby。

UPDATE "stores" SET "phone" = ?, "updated_at" = ? WHERE "stores"."id" = ? [["phone", "1234"], ["updated_at", "2021-01-10 21:39:51.295940"], ["id", 2]]两者都不会起作用。这既不是 SQL 也不是 Rails。它是调试输出,需要稍微解释一下。

UPDATE "stores" SET "phone" = ?, "updated_at" = ? WHERE "stores"."id" = ?是带有值占位符的 SQL。

[["phone", "1234"], ["updated_at", "2021-01-10 21:39:51.295940"], ["id", 2]]是成对的列和它们的值。

将它们放在一起,您将获得 SQL 语句:

UPDATE "stores"
SET "phone" = '1234',
    "updated_at" = '2021-01-10 21:39:51.295940'
WHERE "stores"."id" = 2

这可以在 SQLite 控制台中运行。


推荐阅读