Search code examples
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

  • ModelName.validators seems to work when you filter the returned list for presence validators:

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