Home Rails: get values from length validator for a field in template
Reply: 0

Rails: get values from length validator for a field in template

Christian Benseler
1#
Christian Benseler Published in 2017-11-10 10:25:15Z

I havel a model with validators on some fields. Example:

class Notation < ActiveRecord::Base
  validates :name, presence: true, uniqueness: true
  validates_length_of :name, minimum: 5, maximum: 128
end

is there a way to get those values from minimum and maximum for the :name field in the template (because I want to show there the value of min and max length to the user, and want to do this dynamically, with the template reflecting the values from the model)? In the rails console, I can do something like

Notation.validators_on(:name)

which outputs

#<ActiveRecord::Validations::PresenceValidator:0x00000005428420 @attributes=[:name], @options={}>, #<ActiveRecord::Validations::UniquenessValidator:0x0000000541b8d8 @attributes=[:name], @options={:case_sensitive=>true}, @klass=Notation (call 'Notation.connection' to establish a connection)>, #<ActiveModel::Validations::LengthValidator:0x0000000540baf0 @attributes=[:name], @options={:minimum=>5, :maximum=>128}>

If I get using the array's index

Notation.validators_on(:name)[2]

I have:

#<ActiveModel::Validations::LengthValidator:0x0000000540baf0 @attributes=[:name], @options={:minimum=>5, :maximum=>128}>

but I was wondering if there is another way, maybe passing the type of validation I'm 'queryng', because I can't rely on the order of the array.

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.339041 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO