ruby-on-railsruby

How do I get a list of required fields in a model in Rails?


I am using Ruby on Rails and I have a model with many different required fields. Is there a way to retrieve a list of only the fields that are required? I don't believe ModelName.validators works because I only want the fields that are required. I have also tried ModelName.column_names but that gives me all the fields.


Solution

  • You can use ModelName.validators and filter the returned list for presence validators:

    ModelName
      .validators                                        
      .grep(ActiveRecord::Validations::PresenceValidator) # only presence validators
      .flat_map(&:attributes)                             # only attribute names