【问题标题】:Rails validations and custom callbacks orderingRails 验证和自定义回调排序
【发布时间】:2015-09-20 11:05:43
【问题描述】:

我对我的一个模型进行了以下验证。目标是验证 first_name、last_name 和 shop 的存在。然后之后(但仍然在验证之前),我想运行我的自定义验证:status。

  validates_presence_of :first_name
  validates_presence_of :last_name
  validates_presence_of :shop

  validate :status, :on => :create

def status
  do stuff with first_name and last_name
end

但似乎 :status 在其他验证之前运行,所以我收到 nil first_name 等错误。我该如何纠正这个问题?

【问题讨论】:

  • 为什么需要按顺序运行它们? FWIW Rails 每次都会运行所有验证,即使一个已经失败。
  • before_create 可能会对您有所帮助。

标签: ruby-on-rails validation


【解决方案1】:

如果您不希望在其他验证返回无效的情况下运行自定义验证,请执行以下操作:

def status
  return if errors.present?
  do stuff with first_name and last_name
end

【讨论】:

    【解决方案2】:

    我会尽力提供帮助。如果status 是表中的字段,则必须更改自定义验证名称。比如

    validates_presence_of :first_name
    validates_presence_of :last_name
    validates_presence_of :shop
    
    validate :check_status, :on => :create
    
    def check_status
      if first_name.present? && last_name.present? && shop.present?
        do stuff with first_name and last_name
        errors.add(:status, "you message here.") // if you need a error message
      end
    end
    

    更多信息请点击此处custom validation。希望对你有帮助

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-18
      • 2021-11-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多