Is there a way to validate the true presence of all attributes in a given model object? Or do I have to list each attribute with presence: true?
Thanks for any help.
To get an array of all your model attributes, you can use YourModel.attribute_names. However you cannot really validate the presence of all your attributes (such as the id, created_at) since these will be blank during validation when creating a record.
class YourModel < ActiveRecord::Base
NON_VALIDATABLE_ATTRS = ["id", "created_at", "updated_at"] #or any other attribute that does not need validation
VALIDATABLE_ATTRS = YourModel.attribute_names.reject{|attr| NON_VALIDATABLE_ATTRS.include?(attr)}
validates_presence_of VALIDATABLE_ATTRS
end
Yes, You can add all the attributes in a single line like this :
validates :name, :login, :email, presence: true
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