Rails中的模块路由with form_for(@object)
我有命名空间Controller Entities :: Customers
class Entities::CustomersController < ApplicationController ... end
和命名空间的ActiveRecord模型:
class Entities::Customer < Entities::User end
在我的routes.rb文件中我有:
resources :customers, module: :entities
模块:实体在那里,因为我不想拥有如下路线:
/ entities / customers但仅限于:
/客户 。
问题在我渲染表单时开始:
抛出错误:类的未定义方法`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
好吧,经过一番努力,我找到了解决这个问题的方法:
simple_form_for(@model)生成前缀为实体的路由,因为它不知道路由中有作用域路径。
所以在我的_form
部分我必须手动告诉rails使用哪个路由,具体取决于我的partial中的action_name
helper方法。
<% 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 %>
所有项目的全局解决方案都可以覆盖ApplicationHelper
方法form_with
(目前在Rails 5中):
在aplication_helper.rb中
def form_with(**options) if options[:module] class_name = options[:module].class.name.demodulize.underscore route_name = class_name.pluralize options[:scope] = class_name options[:url] = if options[:module].new_record? send("#{route_name}_path") else send("#{route_name}_path", options[:module]) end options[:module] = nil super end end
所以,如果有像这样的路线
scope module: 'site' do resources :translations end
你可以在_form.html.erb中编码:
<%= form_with(module: @translation) do |form| %>
没有错误