由于我们的电子邮件服务的限制,我们有一个带有电子邮件字段的表 - 排序规则 latin1_swedish_ci
。
当新用户到达时检查此表以查看他是否已经订阅。
出现在用户电子邮件中的字符对于此特定排序规则无效。以 hsıasdf@test.com
Would it be possible to determine before saving if a string will adhere to the collation rules of database?
Is it possible for me to check before any DB trigger to save/create/find; if an entry with this particular email will agree with the collation? Some regex maybe?
最佳答案
在 Ruby 中你可以使用 String#encode
测试在常见编码之间转换字符串。
但是,当您想测试 MySQL 特定的排序规则时,这将无济于事。
你可以做的是使用 transaction :
User.transaction do
if User.create!(email: 'hsıasdf@test.com')
puts "yup its valid"
raise ActiveRecord::Rollback
end
end
不过效果不是很好。如果您希望它在保存之前运行,您可以使用自定义验证。
如果可能,我会使用 MySQL 标准 utf
和 utf8_general_ci
并仅在需要与电子邮件系统交互的应用程序边界进行转换。使用非 UTF-8 编码会给您带来很多麻烦,并且从长远来看可能非常有害,例如,如果更改了不良的电子邮件系统。
您可以选择即时整理:
SELECT users.email COLLATE latin1_swedish_ci AS users.collated_email
FROM users
关于mysql - 检查输入字符串是否符合数据库排序规则,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37407604/