|
| 1 | +# Add ActiveRecord Error Not Tied To Any Attribute |
| 2 | + |
| 3 | +Often the [errors on an ActiveRecord |
| 4 | +object](https://api.rubyonrails.org/v6.1.3.2/classes/ActiveModel/Errors.html) |
| 5 | +are tied to a specific attribute of that object. For instance, when this |
| 6 | +validation is violated |
| 7 | + |
| 8 | +```ruby |
| 9 | +validates :name, presence: true |
| 10 | +``` |
| 11 | + |
| 12 | +Then the error will be tied to `:name`. |
| 13 | + |
| 14 | +With the |
| 15 | +[`ActiveModel::Errors#add`](https://api.rubyonrails.org/v6.1.3.2/classes/ActiveModel/Errors.html#method-i-add) |
| 16 | +method, we can write custom validation logic that ties an error to a specific |
| 17 | +attribute. |
| 18 | + |
| 19 | +```ruby |
| 20 | +validate :quantity_for_bulk_purchase |
| 21 | + |
| 22 | +def quantity_for_bulk_purchase |
| 23 | + return if purchase_type != :bulk |
| 24 | + |
| 25 | + if quantity < 12 |
| 26 | + errors.add(:quantity, "must be greater than 12 for bulk purchases") |
| 27 | + end |
| 28 | +end |
| 29 | +``` |
| 30 | + |
| 31 | +Errors don't have to be tied to specific attribute. They can be tied to the |
| 32 | +object as a whole. This can be better for validations, like the one above, that |
| 33 | +involve multiple attributes. |
| 34 | + |
| 35 | +```ruby |
| 36 | +validate :quantity_for_bulk_purchase |
| 37 | + |
| 38 | +def quantity_for_bulk_purchase |
| 39 | + return if purchase_type != :bulk |
| 40 | + |
| 41 | + if quantity < 12 |
| 42 | + errors.add(:base, "Quantity must be greater than 12 for bulk purchases") |
| 43 | + end |
| 44 | +end |
| 45 | +``` |
| 46 | + |
| 47 | +By using the `:base` symbol, we are ascribing this error to the object as a |
| 48 | +whole. |
| 49 | + |
| 50 | +``` |
| 51 | +> my_object.errors |
| 52 | +#=> #<ActiveModel::Errors:0x00007fccaa5a8740 |
| 53 | + @base= |
| 54 | + #<MyObject:0x00007fcc8a5e9238 |
| 55 | + ... |
| 56 | + @details={:base=>[{:error=>"Quantity must be greater than 12 for bulk purchases"}]}, |
| 57 | + @messages={:base=>["Quantity must be greater than 12 for bulk purchases"]}> |
| 58 | +
|
| 59 | +> my_object.errors.full_messages |
| 60 | +#=> ["Quantity must be greater than 12 for bulk purchases"] |
| 61 | +``` |
0 commit comments