我的一个 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/