ruby-on-railscontrollerroutesnamespacessimple-form-for

Module route in Rails with form_for(@object)


I have namespaced Controller Entities::Customers

class Entities::CustomersController < ApplicationController
...
end

and namespaced ActiveRecord model:

class Entities::Customer < Entities::User

end

in my routes.rb file i have:

 resources :customers, module: :entities

The module :entities is there because i don't want to have routes such as:

/entities/customers but only:

/customers.

The problem starts when i'm rendering my form:

<%= simple_form_for(@customer) do |f| %>
      <%= f.input :email %>
      <%= f.input :password %>
      <%= f.input :name %>
      <%= f.button :submit %>
<% end %>

This throws error: undefined method `entities_customer_path' for Class..

So the error is that rails think that the correct path is with prefix entities.

Rake routes give me:

             Prefix Verb   URI Pattern                   Controller#Action
      customers GET    /customers(.:format)          entities/customers#index
                POST   /customers(.:format)          entities/customers#create
   new_customer GET    /customers/new(.:format)      entities/customers#new
  edit_customer GET    /customers/:id/edit(.:format) entities/customers#edit
       customer GET    /customers/:id(.:format)      entities/customers#show
                PATCH  /customers/:id(.:format)      entities/customers#update
                PUT    /customers/:id(.:format)      entities/customers#update
                DELETE /customers/:id(.:format)      entities/customers#destroy

Solution

  • Ok so after some struggling I've found a solution to this problem:

    The simple_form_for(@model) generate route prefixed with entities, since it doesn't know there is scoped path in routes.

    So in my _form partial i had to manually tell rails which route to use depending on action_name helper method in my partial.

    <%
    case action_name
      when 'new', 'create'
       action = send("customers_path")
       method = :post
      when 'edit', 'update'
       action = send("customer_path", @customer)
       method = :put
    end
    %>
    
    <%= simple_form_for(@customer, url: action, method: method) do |f| %>
          <%= f.input :email %>
          <%= f.input :password %>
          <%= f.input :name %>
          <%= f.button :submit %>
    <% end %>