1

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?

1 Answer 1

3

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
            }
        ]
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

@Anjan send it as form-data and use trip[events_attributes][0][distance] = 300

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.