如何在 Rails 验证中从属性中删除问号?

How to remove question marks from attributes in a Rails validation?

validates :tag, format: { with: /[^?]+/, message:'cannot have question marks') }

我希望此值的验证失败:

tag = "why not?"

并通过这个:

tag = "why not"

我不明白如何简单地按下“?”在带有正则表达式的字符串中。

谢谢!

如果要删除字符串中的 all ?,只需执行以下操作:"why not?".gsub("?", '')

编辑 我刚刚重读了你的问题,你想要正则表达式来验证(呃,我需要咖啡)。

您需要转义 ? 因为正则表达式中的 ? 表示 零之一... 所以只需将您的验证更改为 -> validates :tag, format: { with: /\?/, message:'cannot question marks') }

你可以这样写你的验证:

validates :tag, format: { without: /\?/, message: 'cannot have question marks' }

参考:http://apidock.com/rails/ActiveModel/Validations/HelperMethods/validates_format_of