2013-06-30 65 views
1

我正在重構一個項目,並且我記得我在實現如何放置嵌套對象時遇到了一些麻煩,但我發現this問題很有用。使用Rails 4創建嵌套對象(JSON調用)

所以,據我所知,你需要傳遞一個參數你的相關模型名稱的複數,並添加一個'_attributes'它。它在Rails 3.2.13中運行良好。

現在,這裏是我在軌道4,5:

class TripsController < Api::V1::ApiController 
     def create 
     begin 
      @user = User.find(params[:user_id]) 
      begin 
      @campaign = @user.campaigns.find(params[:campaign_id]) 
      if @trip = @campaign.trips.create(trip_params) 
       render json: @trip, :include => :events, :status => :ok 
      else 
       render json: { :errors => @trip.errors }, :status => :unprocessable_entity 
      end 
      rescue ActiveRecord::RecordNotFound 
      render json: '', :status => :not_found 
      end 
     rescue ActiveRecord::RecordNotFound 
      render json: '', :status => :not_found 
     end 
     end 

     private 

     def trip_params 
     params.require(:trip).permit(:evnt_acc_red, :distance, events_attributes: [:event_type_id, :event_level_id, :start_at, :distance]) 
     end 
    end 

,跳閘模型是這樣的:

class Trip < ActiveRecord::Base 

    has_many :events 
    belongs_to :campaign 
    accepts_nested_attributes_for :events 
end 

所以,我做具有以下JSON一個POST電話:

{"trip":{"evnt_acc_red":3, "distance":400}, "events_attributes":[{"distance":300}, {"distance":400}]} 

而且,即使我沒有得到任何類型的錯誤,也沒有創建任何事件。旅程正在創建正確,但不是嵌套的對象。

有關我應該如何在Rails 4上完成這項工作的任何想法?

回答

3

好了,所以......我被錯誤地發送JSON:

相反的:

{ 
    "trip": { 
     "evnt_acc_red": 3, 
     "distance": 400 
    }, 
    "events_attributes": [ 
     { 
      "distance": 300 
     }, 
     { 
      "distance": 400 
     } 
    ] 
} 

我應該已經發送:

{ 
    "trip": { 
     "evnt_acc_red": 3, 
     "distance": 400, 
     "events_attributes": [ 
      { 
       "distance": 300 
      }, 
      { 
       "distance": 400 
      } 
     ] 
    } 
} 
+0

如何做到這一點使用郵遞員,有什麼建議麼?? – Anjan

+1

@Anjan將它作爲表單數據發送並使用trip [events_attributes] [0] [distance] = 300 – killebytes