Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to return error code in addition to error message in rails active record validation?

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.

like image 877
Andy Wang Avatar asked Oct 30 '13 02:10

Andy Wang


People also ask

What is the difference between validate and validates in rails?

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.

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

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.

What is Active Record in Ruby on Rails?

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.

Why must you validate data before persisting it?

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.


1 Answers

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.

like image 191
jvenezia Avatar answered Oct 11 '22 18:10

jvenezia