Rails 7: Nested resources/forms not working

Hi,

i have three models:


class Checklist < ApplicationRecord
  belongs_to :page
	has_many :groups

	has_rich_text :description

#	validates_presence_of :title
end



class Group < ApplicationRecord
  belongs_to :checklist
end


class Page < ApplicationRecord
	has_many :checklists
	has_rich_text :description
end

A page can have one or many checklists. A Checklist can have one or more Groups.

All Associations are created.

On the pages editpage i created a form like this:

<% @page.checklists.each do |cl| %>

    <%= form_with(model: [@page, cl]) do |f| %>

        .... more code => text fields etc

    <% end %>

<% end %>

And the checklist controller:

def create

    @page = Page.find(params[:page_id])

    @checklist = @page.checklists.build

   

    if @checklist.save

      notice = nil

    else

      notice = @checklist.errors.full_messages.join('.') << '.'

    end

    redirect_to edit_page_path(@page), notice: notice

  end

There I can easily create a checklist for this page.

 


 

Now i want to do the same with groups for checklists. But there is my problem, it won’t work.

Here is the form:

<%= form_for [@page, @checklist, @group] do |form|%>
    ... more code => text fields etc
<% end %>

This is my create action for groups:

def create
    @page = Page.find(params[:page_id])
	@checklist = Page.checklists.find(params[:checklist_id])
    @group = @checklist.groups.build

    if @group.save
		notice = nil
    else
		notice =  @group.errors.full_messages.join('.') << '.'
    end
		redirect_to edit_page_checklist_path(@checklist), notice: notice
  end

Is there any other code needed to help me?

Do you have something like

resources :pages do
  resources :checklists do
    resources :groups
  end
end

in your routes.rb? I would avoid double nested resources.

<%= form_for [@checklist, @group] do |form| %> 

should be enough to create a group, since @checklist is always linked to a page. Second, edit_page_checklist_path needs the page as param. Without double nesting you don’t have @page, but you can take it from @checklist:

redirect to edit_page_checklist_path([@checklist.page, @checklist]), notice: notice