简体   繁体   中英

Create Nested Object with Rails 4 (JSON call)

I am refactoring a project, and I remembered that I had some troubles in realizing how to put a nested object, but I found this question useful.

So, as I understand it, you needed to pass as a parameter your associated model name in plural and add a '_attributes' to it. It worked great in Rails 3.2.13.

Now, here is what I have in Rails 4:

    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

And the Trip model looks like this:

class Trip < ActiveRecord::Base

  has_many :events
  belongs_to :campaign
  accepts_nested_attributes_for :events
end

So, I am doing a POST call with the following JSON:

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

And, even though I don't get any kind of error, no event is being created. The trip is being created correctly, but not the nested object.

Any thoughts on what should I do to make this work on Rails 4?

Alright, so... I was sending the JSON wrongly:

Instead of:

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

I should have been sending:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM