Briefly, I have a model User with name, email and comment as attributes.
validates_presence_of :name
validates_presence_of :email
So 'name' and 'email' are required but not 'comment'.
my_user = User.new
I'd like to find a way to test like my_user.name.required? or User.name.required? kind of thing.
My goal is to create a form and to add a specific class dynamically to the form item span or td depending on if this item is set as "validates_presence_of"
I tried to search for it but did not find anything about. Is there a easy way to do this?
Thanks
I can't comment as I don't have 50 rep, but on Rails 5+ this doesn't work anymore. You can do:
ModelName.validators_on(:attribute).any? { |v| v.class == ActiveRecord::Validations::PresenceValidator }
There isn't a single method you can call to handle this, but this post talks about creating a helper method do to what it sounds like you're after.
module InputHelper
def required?(obj, attribute)
target = (obj.class == Class) ? obj : obj.class
target.validators_on(attribute)
.map(&:class)
.include?(ActiveModel::Validations::PresenceValidator)
end
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With