Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails: How to 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"

I tried to search for it but did not find anything about. Is there a easy way to do this?

Thanks

like image 643
oldergod Avatar asked Oct 20 '11 01:10

oldergod


2 Answers

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 }
like image 114
FanaHOVA Avatar answered Oct 13 '22 08:10

FanaHOVA


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
like image 36
Chelsea Avatar answered Oct 13 '22 08:10

Chelsea