[英]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.