AndrewJL
AndrewJL

Reputation: 128

Rails validate all attributes in object

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

Answers (3)

AbM
AbM

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

Tobias
Tobias

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

Padhu
Padhu

Reputation: 1580

Yes, You can add all the attributes in a single line like this :

validates :name, :login, :email, presence: true

Upvotes: 2

Related Questions