2

我有命名空间控制器实体::客户

class Entities::CustomersController < ApplicationController
...
end

和命名空间的 ActiveRecord 模型:

class Entities::Customer < Entities::User

end

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

 resources :customers, module: :entities

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

/entities/customers但仅限:

/客户

当我呈现我的表单时,问题就开始了:

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

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

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

耙路线给我:

             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
4

2 回答 2

1

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

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

因此,在我的_form部分中,我必须根据action_name我的部分中的辅助方法手动告诉 rails 使用哪条路线。

<%
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 %>
于 2016-07-07T16:50:01.293 回答
0

所有项目的全局解决方案都可以是覆盖ApplicationHelper方法form_with(目前在 Rails 5 中):

application_helper.rb

  def form_with(**options)
    if options[:model]
      class_name = options[:model].class.name.demodulize.underscore
      create_route_name = class_name.pluralize

      options[:scope] = class_name
      options[:url] = if options[:model].new_record?
                        send("#{create_route_name}_path")
                        # form action = "customers_path"
                      else
                        send("#{class_name}_path", options[:model])
                        # form action = "customer/45"
                      end

      # post for create and patch for update:
      options[:method] = :patch if options[:model].persisted?

      options[:model] = nil

      super
    end
  end

这样,如果有类似的路线

 scope module: 'site' do
  resources :translations
 end

您可以在 _form.html.erb 中编写代码:

<%= form_with(model: @translation, method: :patch) do |form| %>

没有错误

于 2018-11-09T16:09:11.353 回答