簡體   English   中英

在Rails 5中對一個模型進行兩種不同的驗證

[英]Two differente validations for one Model in Rails 5

我的Rails 5應用程序中有一個Transfer模型。 在我的控制器中,我有一個create和quotation方法。 現在的挑戰是,我想對每種方法應用不同的驗證。

當我創建一個新的Transfer時,我想驗證整個對象。 但是在我的報價方法中,我只想應用一些驗證。 例如,要創建轉機,我需要驗證乘客,但是要返回報價,則不需要乘客。

最好的方法是什么?

如何使用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 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM