mysql - 为什么我的 Rails 函数在 SQLite 中有效,但在 MySQL 中无效?

标签 mysql ruby-on-rails sqlite activerecord

我的一个 Rails 模型中有这个功能:

def delete_unactivated_users    
  expiry_time = Time.zone.now - USER_ACTIVATION_TIME
  User.where("admin == ? and activated == ? and created_at < ?", false, false, expiry_time).destroy_all
end

development 模式下,使用 SQLite,它工作得非常好。但是在 production 中,使用 MySQL,我得到了这个语法错误:

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 '== 0 and activated == 0 and created_at < '2014-05-20 10:35:55')' at line 1: SELECT `users`.* FROM `users`  WHERE (admin == 0 and activated == 0 and created_at < '2014-05-20 10:35:55'))

如何修复我的函数,使其在 SQLite 和 MySQL 中同样有效?

这将是我的 schema.rb 文件的摘录:

create_table "users", force: true do |t|
  ...
  t.boolean  "admin",                         default: false
  t.boolean  "activated",                     default: false
  ...
end

感谢您的帮助。

最佳答案

MySql 不使用 == - 它使用 = 来测试相等性以及设置值。

将其更改为 =,因为这是 SQL 标准。

  User.where("admin = ? and activated = ? and created_at < ?", false, false, expiry_time).destroy_all

关于mysql - 为什么我的 Rails 函数在 SQLite 中有效,但在 MySQL 中无效?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23952844/

相关文章:

Java JDBC 将 ResultSet 存储在 ArrayList 中

android - 如何获取项目ID以及android网格中的项目位置

java - android中导入数据库的问题

php - CodeIgniter:从数据库(表)填充表(HTML/表单)

java - 如何使用java变量向mysql插入值

ruby-on-rails - 是否可以使用带有 Active Record 的 SQL 注入(inject)来修改数据库

html - Rails CSS、JS 和 jQuery TypeErrors(适用于 Windows)

php - 在页面中我有 for 循环函数吗?在 for($i=0;$i<=$max;$i++){ Size 查询中只从 mysql 数据库检索一行?

php - UTF-8贯穿始终

javascript - Javascript/jQuery/Coffeescript 在 Ruby on Rails 中的作用是什么?