Unmatched Constraint error with Form_for with Triple Nesting

67 views Asked by At

I am making an events app where each event can have multiple to do lists each with their own tasks.

I am struggling with the third level nesting of the tasks (todo_items)

Here are my models:

Event.rb

has_many :todo_lists, :dependent => :destroy
has_many :todo_items, :through => :todo_lists 

accepts_nested_attributes_for :todo_lists
accepts_nested_attributes_for :todo_items

Todo_list.rb

 has_many :todo_items, :dependent => :destroy

 accepts_nested_attributes_for :todo_items

 belongs_to :event

Todo_item.rb

belongs_to :todo_list

Todo_list_Controller.rb

def set_todo_list
  @todo_list = @event.todo_lists.find(params[:id])
end

def set_event
  @event = Event.find(params[:event_id])
end

def todo_list_params
  params.require(:todo_list).permit(:title, :description, :event_id)
end

Todo_items_Controller.rb

def set_todo_list
  @todo_list = TodoList.find(params[:todo_list_id])
end

def set_todo_item
  @todo_item = @todo_list.todo_items.find(params[:id])
end

def todo_item_params
  params[:todo_item].permit(:content, :todo_list_id)
end

routes.rb

resources :events do
    resources :todo_lists do
      resources :todo_items do
        member do
          patch :complete
        end
      end
    end
end

If any other code is needed I Will update! Thanks in advance!

I have done my best to nest the objects. I can add tasks (todo_items) to a todo_list but I cannot delete or complete them.

The error comes from the todo_LIST_controller not the todo_ITEMS_controller

Error Log:

ActiveRecord::RecordNotFound (Couldn't find TodoList with 'id'=5 [WHERE "todo_lists"."event_id" = ?]):
2

There are 2 answers

4
Dillon On

I think you'll have to make sure that the routes are nested properly

from events to the todo_items

resources :event do
  resources :todo_lists do
     resources :todo_items
  end
end

I don't know how you set up your routes but the above is to illustrate what I'm trying to say. Hope that helps

0
Ryan Neill On

It was a routing error with the redirect path.

The wrong route was:

redirect_to event_todo_list_path(@event)

simply missing the @todo_list paramater.

redirect_to event_todo_list_path(@event, @todo_list)