ruby-on-railsruby

How can I test if an attribute of a class object is required in the model policy?


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"


Solution

  • 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