2016-06-08 56 views
0

我有一個遠程表單,它主要在一個表單中提交兩個表單。一個用於Address另一個用於User現在我想要做的就是在JSON中渲染錯誤。在JSON中呈現兩個不同的模型錯誤

我能單獨返回象這樣的錯誤:

if current_user.errors.any? || [email protected] 
    respond_to do |format| 
    format.json { render json: @address.errors, status: :unprocessable_entity } 
    end 
end 

現在有他們觸發兩個用戶模型和地址錯誤的情況下。我怎樣才能渲染這兩個錯誤,所以@address.errorscurrent_user.errors。我試圖將它們合併爲散列,但是因爲它們屬於ActiveModel :: Errors,所以無法這樣做。錯誤通常返回這樣的,如果你檢查它:

#<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"}]}> 

所以我想要搞清楚的是,如果有合併成一個這樣的方式,這樣我就可以返回。

+0

有btween地址和用戶的任何關係? –

回答

1

如何像:

if current_user.errors.any? || [email protected] 
    respond_to do |format| 
    format.json { render json: {address_errors: @address.errors, current_user_errors: current_user.errors}, status: :unprocessable_entity } 
    end 
end 

現在你有一個JSON響應,這是與2項的哈希:一個用於address_errors,一個用於current_user_errors。

0

你可以用這個嘗試:

format.json { render json: { @address.errors, @user.errors }, status: :unprocessable_entity }