Rails 3 - Custom Validation

后端 未结 2 1785
庸人自扰
庸人自扰 2021-02-01 04:50

I\'m somewhat confused by my options for custom validations in Rails 3, and i\'m hoping that someone can point me in the direction of a resource that can help with my current is

2条回答
  •  臣服心动
    2021-02-01 05:08

    You can use the ActiveModel::Validator class like so:

    class VehicleValidator < ActiveModel::Validator
      def validate(record)
        return true if # custom model_year and trip logic
        record.errors[:base] << # error message
      end
    end
    
    class Vehicle < ActiveRecord::Base
      attr_accessible :make_id, :model_id, :trim_id, :model_year_id
      belongs_to :trim
      belongs_to :model_year
    
      include ActiveModel::Validations
      validates_with VehicleValidator
    end
    

提交回复
热议问题