0

i try the gem validates_operator. I need to custom my message for this validation:

validates :arrival_date, :departure_date, overlap: {
scope:"place_id",
message_title: "Error",
message_content:"Impossible to booking this place for this date" }

but i have the default message of simple form : "Please review the problems below"

Thx for the future answer.

1 Answers1

1

You can also create methods that verify the state of your models and add messages to the errors collection when they are invalid. You must then register these methods by using the validate (API) class method, passing in the symbols for the validation methods' names.

You can pass more than one symbol for each class method and the respective validations will be run in the same order as they were registered.

The valid? method will verify that the errors collection is empty, so your custom validation methods should add errors to it when you wish validation to fail:

class Invoice < ApplicationRecord
  validate :expiration_date_cannot_be_in_the_past,
    :discount_cannot_be_greater_than_total_value

  def expiration_date_cannot_be_in_the_past
    if expiration_date.present? && expiration_date < Date.today
      errors.add(:expiration_date, "can't be in the past")
    end
  end

  def discount_cannot_be_greater_than_total_value
    if discount > total_value
      errors.add(:discount, "can't be greater than total value")
    end
  end
end

By default, such validations will run every time you call valid? or save the object. But it is also possible to control when to run these custom validations by giving an :on option to the validate method, with either: :create or :update.

class Invoice < ApplicationRecord
  validate :active_customer, on: :create

  def active_customer
    errors.add(:customer_id, "is not active") unless customer.active?
  end
end
Rush0312
  • 159
  • 5