Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 255
Alex Avatar asked Oct 20 '25 01:10

Alex


2 Answers

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
like image 158
spickermann Avatar answered Oct 21 '25 16:10

spickermann


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
like image 26
Vibol Avatar answered Oct 21 '25 16:10

Vibol



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!