Sebastian Jennings Almnes Sebastian Jennings Almnes - 4 months ago 5x
JSON Question

render two different model errors in JSON

I have a remote form, that essentially submits two forms in one. One for

the other for
now what I'd like to do is render the errors in JSON.

I'm able to return the errors individually like this:

if current_user.errors.any? || !
respond_to do |format|
format.json { render json: @address.errors, status: :unprocessable_entity }

now there's the case where they trigger an error on both User model and Address. How can I render both errors so
. I've tried to merge them as hashes, but as they belong to ActiveModel::Errors it's unable to do so. An error usually returns like this if you inspect it:

#<ActiveModel::Errors:0x007fbe094edda0 @base=#<Address id: nil, street_address: "Lorem ipsum", city: nil, state: nil, zip_code: "0000", country: nil, user_id: 1, created_at: nil, updated_at: nil, latitude: 10.92876, longitude: 52.23023, trashed: false>, @messages={:zip_code=>["No zip code matches this"]}, @details={:zip_code=>[{:error=>:inclusion, :value=>"0000"}]}>

so what I'm trying to figure out is if there's a way to merge this into one, so I can just return that.


How about something like:

if current_user.errors.any? || !
  respond_to do |format|
    format.json { render json: {address_errors: @address.errors, current_user_errors: current_user.errors}, status: :unprocessable_entity }

Now you have a json response that is a hash with 2 entries: one for address_errors and one for current_user_errors.