Rails中带有form_for(@object)的模块路由 [英] Module route in Rails with form_for(@object)

查看:97
本文介绍了Rails中带有form_for(@object)的模块路由的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有命名空间的Controller Entities :: Customers

I have namespaced Controller Entities::Customers

class Entities::CustomersController < ApplicationController
...
end

和带名称空间的ActiveRecord模型:

and namespaced ActiveRecord model:

class Entities::Customer < Entities::User

end

在我的route.rb文件中,我有:

in my routes.rb file i have:

 resources :customers, module: :entities

模块:entities在那里,因为我不想拥有诸如以下的路线:

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

/entities/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 %>

这会引发错误:类的未定义方法"entities_customer_path".

所以错误是Rails认为正确的路径带有前缀实体.

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

耙道给了我

             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

推荐答案

好吧,经过一番挣扎之后,我找到了解决该问题的方法:

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

simple_form_for(@model)生成以实体为前缀的路由,因为它不知道路由中存在作用域的路径.

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

因此,在我的_form部分中,我必须根据我的部分中的action_name辅助方法手动告诉Rails使用哪个路由.

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 %>

这篇关于Rails中带有form_for(@object)的模块路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆