Search code examples
ruby-on-railsrails-api

Rails 5 API accepts_nested_attributes_for not works


I'm trying to save an event with tasks using accepts_nested_attributes_for but it doesn't work.

My models:

class Event < ApplicationRecord
  has_many :tasks
  accepts_nested_attributes_for :tasks, :allow_destroy => true
end

class Task < ApplicationRecord
  belongs_to :event, optional: true
end

Event params method

params.require(:event).permit(:name, tasks_attributes: [ :name ])

Post call

{
    "name": "event",
    "tasks_attributes": [
        { "name": "Task 1" }    
    ]
}

What do you think that can be?


Solution

  • Bruno!

    You actually have to use an envelope for the object you're trying to post.

    {
        "event": {
            "name": "event",
            "tasks_attributes": [
                { "name": "Task 1" }    
            ]
        }
    }