Starkers
Starkers

Reputation: 10541

Datatype model validation

In Ruby on Rails, I can't seem to find a validation model method to check for data-type.

I was hoping for something like

validates :name, datatype: :integer

but there is nothing on http://guides.rubyonrails.org/testing.html

If such a test not required? Is it because the database engine (mysql or whatever) itself would reject information with a wrong data-type?

Upvotes: 2

Views: 2838

Answers (3)

techvineet
techvineet

Reputation: 5111

There is a validation for this in Rails

validates_numericality_of :value, :only_integer: true

Upvotes: 1

Salil
Salil

Reputation: 47482

It seems you are new to Rails there are already predefined validations in rails Ref Active Record Validations in Rails

validates :name, numericality: true

or

validates :name, numericality: { only_integer: true }

Upvotes: 4

Sabyasachi Ghosh
Sabyasachi Ghosh

Reputation: 2785

You can do something like

validates :your_field, :numericality => { :greater_than_or_equal_to => 0 }

please check the link

Validation for non-negative integers and decimal values

Upvotes: 1

Related Questions