Reputation: 128
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.
Upvotes: 3
Views: 4721
Reputation: 7779
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
Upvotes: 5
Reputation: 4653
You can get all attribute names in an Array
with the method .attributes_names
.
Then everything you have to do is to add this array
to the validates_presence_of
method.
Example:
class Model < ActiveRecord::Base
validates_presence_of attribute_names.reject { |attr| attr =~ /id|created_at|updated_at/i }
end
Upvotes: 1
Reputation: 1580
Yes, You can add all the attributes in a single line like this :
validates :name, :login, :email, presence: true
Upvotes: 2