Rails 3 - Custom Validation

后端 未结 2 1780
庸人自扰
庸人自扰 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
    
    0 讨论(0)
  • 2021-02-01 05:23

    you can use custom validation method, as described here:

    class Vehicle < ActiveRecord::Base
      validate :model_year_valid_for_trim
    
      def model_year_valid_for_trim
        if #some validation code for model year and trim
          errors.add(:model_years, "some error")
        end
      end
    
    end
    
    0 讨论(0)
提交回复
热议问题