【问题标题】:App is crashing when using validates_uniqueness_of on Rails with Mongoid?在带有 Mongoid 的 Rails 上使用 validates_uniqueness_of 时应用程序崩溃?
【发布时间】:2019-06-15 17:57:23
【问题描述】:

我在 Rails 上使用 Mongoid,并在模型 Quote 上添加了 validates_uniqueness_of :quote

但只要有重复记录,应用就会崩溃并显示此消息:

消息:报价验证失败。摘要:以下错误 已找到:报价已被采纳 解决方法:尝试坚持 包含有效数据的文档或删除验证。

这是我的模型:

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

如果是唯一的则保存,如果不是则忽略,但永远不会崩溃。

【问题讨论】:

    标签: ruby-on-rails-5 mongoid


    【解决方案1】:

    您的应用实际上并没有崩溃,它只是抛出了一个异常。

    调用save!方法时,!表示会触发validation,验证失败时会抛出异常。

    更好的方法是使用rescue 处理异常,但如果您不关心验证结果,请改用save

    【讨论】:

      猜你喜欢
      • 2023-03-24
      • 1970-01-01
      • 2023-03-25
      • 2019-04-16
      • 2011-07-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多