Rails中一个模型的两个不同验证5

时间:2018-01-16 18:24:08

标签: ruby-on-rails ruby-on-rails-5

我的Rails 5应用程序中有一个Transfer模型。 在我的控制器中,我有一个创建和引用方法。我现在的挑战是我想为每种方法应用不同的验证。

当我创建一个新的Transfer时,我想验证整个对象。但在我的引用方法中,我想仅应用一些验证。例如,要创建一个转移我需要验证乘客,但要返回报价,不需要乘客。

这样做的最佳方式是什么?

1 个答案:

答案 0 :(得分:0)

如何使用before_action回调来验证每个操作?

class Transfer < ApplicationRecord
  before_create :passengers_present
  before_action :quotation_valdiation, only: :quotation
  ...

  private

  def passengers_present
    errors.add("must have passengers") unless passengers.count > 0
  end

  def quotation_validation
    errors.add("failure message") if failure
  end
end