Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby on Rails: errors.add_to_base vs. errors.add

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!

like image 641
Tony Avatar asked Apr 01 '09 17:04

Tony


People also ask

What is errors [: base in rails?

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.

How do I validate in Ruby on Rails?

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".

Can we save an object in the DB if its validations do not pass?

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.

How does validation work in Rails?

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.


2 Answers

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

like image 167
GSP Avatar answered Sep 19 '22 07:09

GSP


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).

like image 26
MarkusQ Avatar answered Sep 19 '22 07:09

MarkusQ