Ask A Question

Notifications

You’re not receiving notifications from this thread.

Using form_with produces odd results for nested namespaced resources.

Chris Born asked in Rails

I'm having an issue with sharing a the new and edit form for a shallow nested resource in a module/namespace.

Most everything works as expected. The issue I'm running into is using form_with and the model: argument.

<%= form_with model: [:admin, @account, @invoice], local: true do |f| %>
...
<% end %>

The form on the #edit route generates the correct path when @invoice is set and @account is set with @account = @invoice.account

However, the same form used from #new is generating admin_accounting_account_accounting_invoices_path instead of the expected admin_accounting_account_invoices_path. If @account is nil at this point then it generates admin_accounting_schedules_path, however if I actually set @account to the current account of /admin/accounting/accounts/3/new then it generates admin_accounting_account_accounting_invoices_path

Is this a limitation of form_with model: around modularized models in namespaces?

I know I can override with url and duplicate the form in new.html.erb and edit.html.erb but it seems the I may be missing something as this isn't that far from Rails conventions.

# routes.rb
namespace :admin
  namespace :accounting do
    resources :accounts, only: [:index, :show] do
      resources :invoices, shallow: true
    end
  end
end

The models are in an Accounting module as are the controllers:

# => app/models/accounting/accounts.rb
# => app/models/accounting/invoices.rb

# => app/controllers/admin/accounting/accounts.rb
# => app/controllers/admin/accounting/invoices.rb

These are the relevant paths generated from routes:

admin_accounting_accounts_path
admin_accounting_account_invoices_path      GET     /admin/accounting/accounts/:account_id/invoices(.:format)       admin/accounting/invoices#index
                                            POST    /admin/accounting/accounts/:account_id/invoices(.:format)       admin/accounting/invoices#create
new_admin_accounting_account_invoice_path   GET     /admin/accounting/accounts/:account_id/schedules/new(.:format)  admin/accounting/schedules#new
edit_admin_accounting_account_invoice_path  GET     /admin/accounting/invoices/:id/edit(.:format)                   admin/accounting/schedules#edit
admin_accounting_invoice_path               GET     /admin/accounting/invoices/:id(.:format)                        admin/accounting/invoices#show
                                            PATCH   /admin/accounting/invoices/:id(.:format)                        admin/accounting/invoices#update
Reply
Join the discussion
Create an account Log in

Want to stay up-to-date with Ruby on Rails?

Join 82,464+ developers who get early access to new tutorials, screencasts, articles, and more.

    We care about the protection of your data. Read our Privacy Policy.