Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 320
AndrewJL Avatar asked Feb 06 '26 11:02

AndrewJL


2 Answers

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
like image 141
AbM Avatar answered Feb 08 '26 23:02

AbM


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

validates :name, :login, :email, presence: true
like image 25
Padhu Avatar answered Feb 08 '26 23:02

Padhu



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!