Sebastian Jennings Almnes Sebastian Jennings Almnes - 6 months ago 12
JSON Question

render two different model errors in JSON

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

Address
the other for
User
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? || !@address.save
respond_to do |format|
format.json { render json: @address.errors, status: :unprocessable_entity }
end
end


now there's the case where they trigger an error on both User model and Address. How can I render both errors so
@address.errors
and
current_user.errors
. 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.

Answer

How about something like:

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

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