user4965201
user4965201

Reputation: 973

Ruby on Rails check the datatype length limit

I have a Rails App and I am using an EachValidator method to check the length of the attribute and showing the error according to limit

the validation goes like this

validates :name, :presence => {
      :message => 'Please enter name'
  }, :string => self.columns_hash["name"].type

now in the :string custom Validation I am right now passing the datatype of the name column, but i want to pass the datatype length instead. How can i achieve this ?

Upvotes: 0

Views: 1165

Answers (3)

Jyoti mishra
Jyoti mishra

Reputation: 597

Please try this,

 validates :name, :presence => {
          :message => 'Please enter name'
          }, :length => {
                  :maximum => columns_hash['name'].limit
              }

Let me know if it is working fine.

Upvotes: 2

David
David

Reputation: 3610

If I understand you correctly you, there is a gem available for this:

gem 'validates_lengths_from_database'

Then in your model simply put:

validates_lengths_from_database

Which will generate validations based on the schema for maximum lengths of string and text fields.

Upvotes: 0

Brad
Brad

Reputation: 8668

validates :name, :presence => {
          :message => 'Please enter name'
          }, :length => { maximum: 255 } # 255 for a string data type

Upvotes: 0

Related Questions