Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails validate type date?

I think i might be dreaming, but i think i read somewhere that you can validate the type of an attribute of an object before you save it? Something like validates :transaction_date, :type => Date and that will make sure that its a date?

Is this possible in Rails 3.2? i am trying to find evidence of this on the net. i have already looked here at the rails api and i am going through the ActiveRecord support.

like image 729
TheLegend Avatar asked Sep 16 '13 15:09

TheLegend


People also ask

What is the difference between validate and validates in rails?

So remember folks, validates is for Rails validators (and custom validator classes ending with Validator if that's what you're into), and validate is for your custom validator methods.

How does validation work in Rails?

Rails validation defines valid states for each of your Active Record model classes. They are used to ensure that only valid details are entered into your database. Rails make it easy to add validations to your model classes and allows you to create your own validation methods as well.

How do I bypass validation?

A very common way to skip validation is by keeping the value for immediate attribute as 'true' for the UIComponents. Immediate attribute allow processing of components to move up to the Apply Request Values phase of the lifecycle. scenario: While canceling a specific action, system should not perform the validation.


2 Answers

As a complement to the other answers, note that you can define a custom validator to let you use exactly the syntax you proposed:

validates :transaction_date, :type => Date

as follows:

class TypeValidator < ActiveModel::EachValidator
  def validate_each(record, attribute, value)
    record.errors.add attribute, (options[:message] || "is not of class #{options[:with]}") unless
      value.class == options[:with]
  end
end

Of course, if you want to allow subclasses, you could change the test to use kind_of?.

like image 84
Peter Alfvin Avatar answered Oct 01 '22 07:10

Peter Alfvin


Rails doesn't support this directly; the closest it comes is probably validates_format_of, or supplying your own custom validator.

I think what you want is the validates_timeliness gem. It not only validates that something is a valid date, but you can specify whether it should be before or after today and various other date range checks.

like image 34
sockmonk Avatar answered Oct 01 '22 07:10

sockmonk