使用 Mongoid 在 Rails 上使用 validates_uniqueness_of 时应用程序崩溃?
App is crashing when using validates_uniqueness_of on Rails with Mongoid?
我在 Rails 上使用 Mongoid,并在模型 Quote
上添加了 validates_uniqueness_of :quote
。
但是每当有重复记录时,应用程序就会崩溃并显示此消息:
message: Validation of Quote failed. summary: The following errors
were found: Quote is already taken resolution: Try persisting the
document with valid data or remove the validations.
这是我的模型:
class Quote
include Mongoid::Document
field :quote, type: String
field :author, type: String
field :author_about, type: String
field :tags, type: String
validates_uniqueness_of :quote
end
这就是我想要做的:
if @quotedb.save!
return true
else
return false
end
它应该保存它是否唯一,如果不是则忽略,但永远不会崩溃。
您的应用实际上并没有崩溃,它只是抛出了一个异常。
当你调用save!
方法时,!
表示它会触发validation,当验证失败时,它会引发异常。
更好的方法是使用 rescue
处理异常,但如果您不关心验证结果,请改用 save
。
我在 Rails 上使用 Mongoid,并在模型 Quote
上添加了 validates_uniqueness_of :quote
。
但是每当有重复记录时,应用程序就会崩溃并显示此消息:
message: Validation of Quote failed. summary: The following errors were found: Quote is already taken resolution: Try persisting the document with valid data or remove the validations.
这是我的模型:
class Quote
include Mongoid::Document
field :quote, type: String
field :author, type: String
field :author_about, type: String
field :tags, type: String
validates_uniqueness_of :quote
end
这就是我想要做的:
if @quotedb.save!
return true
else
return false
end
它应该保存它是否唯一,如果不是则忽略,但永远不会崩溃。
您的应用实际上并没有崩溃,它只是抛出了一个异常。
当你调用save!
方法时,!
表示它会触发validation,当验证失败时,它会引发异常。
更好的方法是使用 rescue
处理异常,但如果您不关心验证结果,请改用 save
。