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.
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
How do I get a list of required fields in a model in Rails?
You can get it by calling:
# Refactor if needed
Model.validators.select{ |v| v.instance_of?(ActiveRecord::Validations::PresenceValidator) }.map{ |v| v.attributes }.flatten
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