简体   繁体   中英

Two differente validations for one Model in Rails 5

I have a Transfer model in my Rails 5 app. In my controller I have a create and a quotation method. My challenge is now that I want to apply differente validations for each method.

When I create a new Transfer I want to validate the entire object. But in my quotation method I want to apply just some of the validations. For example to create a Transfer I need to validate the passengers, but to return the quotation there are no passengers needed.

What would be the best way of doing this?

How about using before_action callbacks to validate each 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 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM