In rails activerecord validation, normally if a validation fails, it will add an error message in the errors attribute of models, however our clients demands an error code be returned in addition to error message, for example, we have a Bill model, which has a msisdn attribute, if msisdn is null, the error code is 101, if the msisdn doesn't complaint with MSISDN format, the error code is 102, when the client submits a request through REST interface, and if the validation fails, we should return a json object like
bill: {
error_code: 101,
error_message: "msisdn can't be null"
}
Is there a way to tell activerecord to generate an error code in addition to error messages? Thanks a lot.
So remember folks, validates is for Rails validators (and custom validator classes ending with Validator if that's what you're into), and validate is for your custom validator methods.
If any validations fail, the object will be marked as invalid and Active Record will not perform the INSERT or UPDATE operation. This helps to avoid storing an invalid object in the database. You can choose to have specific validations run when an object is created, saved, or updated.
Active Record is the M in MVC - the model - which is the layer of the system responsible for representing business data and logic. Active Record facilitates the creation and use of business objects whose data requires persistent storage to a database.
Data validation (when done properly) ensures that data is clean, usable and accurate. Only validated data should be stored, imported or used and failing to do so can result either in applications failing, inaccurate outcomes (e.g. in the case of training models on poor data) or other potentially catastrophic issues.
Rails 5 will include a similar feature with foo.errors.details
. You can easily use this to build better api errors.
class Person < ActiveRecord::Base
validates :name, presence: true
end
person = Person.new
person.valid?
person.errors.details
# => {name: [{error: :blank}]}
If you prefer code errors as numbers, you can easily match numbers with the error keys.
For Rails 3 & 4 you can use this gem https://github.com/cowbell/active_model-errors_details witch is the exact same feature backported.
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