I have read that errors.add_to_base should be used for errors associated with the object and not a specific attribute. I am having trouble conceptualizing what this means. Could someone provide an example of when I would want to use each?
For example, I have a Band model and each Band has a Genre. When I validate the presence of a genre, if the genre is missing should the error be added to the base?
The more examples the better
Thank you!
Effectively Use Rails 5 Validation Methods errors[:base] = msg Adds an error message related to the overall object state itself and not the value of any particular attribute. Make your error messages complete sentences, because Rails does not do any additional processing of them to make them readable.
This helper validates the attributes' values by testing whether they match a given regular expression, which is specified using the :with option. Alternatively, you can require that the specified attribute does not match the regular expression by using the :without option. The default error message is "is invalid".
Some methods will trigger validations, but some will not. This means that it's possible to save an object in the database in an invalid state if you aren't careful. The following methods trigger validations, and will save the object to the database only if the object is valid: create.
Rails validation defines valid states for each of your Active Record model classes. They are used to ensure that only valid details are entered into your database. Rails make it easy to add validations to your model classes and allows you to create your own validation methods as well.
It's worth noting (since this shows up in the search engines, which is how I found it) that this is deprecated. The Rails 3 way of doing it is:
errors[:base] << "Error message"
or
errors.add(:base, "Error message")
http://apidock.com/rails/ActiveRecord/Errors/add_to_base
http://apidock.com/rails/v3.2.8/ActiveModel/Errors/add
A missing genre would be a field error. A base error would be something like an exact duplicate of an existing record, where the problem wasn't tied to any specific field but rather to the record as a whole (or at lest to some combination of fields).
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