"Create"路由路径帮助程序



我发现资源路由方法非常方便,但我完全讨厌它不会创建createdestroy路径助手。

我明白写作

<% form_for(@object) %> 

应该自动获取路由名称,并且我们可以使用数组或符号来自动获取命名空间/前缀(如果它们存在(,但是我有很多路由具有复杂的scope定义,并且无法获得create_xxx助手完全让我烦恼

没有比写更简单的解决方案吗?(我试图在生成帮助程序时保留默认的 RESTful URL(

complicated_scope do
  resources :my_resources, except: [:create, :destroy] do
    post '', on: :collection, action: :create, as: 'create' # plus this generates a pluralized version, not very intuitive `create_complicated_scope_my_resourceS_path`
    delete '', on: :member, action: :destroy, as: 'destroy'
  end
end

编辑。我的"范围有点复杂"的例子

# Company access routes under /company/
namespace :company do
  # I need a company id for all nested controllers (this is NOT a resource strictly speaking, and using resources :companies, only: [] with 'on: :collection' doesn't generate appropriate urls)
  scope ':company_id' do
    # Company administrators
    namespace :admin do
      # There is a lot of stuff they can do, not just administration
      namespace :administration do
        # There are several parameters grouped in different controllers
        resources :some_administrations do
          ... # finally RESTful actions and others here
        end
      end
    end
  end
end

资源路由确实会创建createdestroy帮助程序,但它们是由所发出的 HTTP 请求的类型(分别为 POST 和 DELETE(隐含的,因此路由帮助程序方法应该可以正常工作。

假设您有以下路由定义:

complicated_scope do
  resources :my_resources
  end
end

举一个简单的例子,在删除的情况下,你可以使用命名路由,如下所示:

link_to "Delete [resource]", complicated_scope_resource_path(id: @my_resource.id), method: :delete

由于 HTTP 谓词消除了控制器操作的歧义,因此帮助程序方法路由到控制器的销毁方法。

或者,您也应该能够使用数组语法。

link_to "Delete [resource]",  [:complicated_scope, @my_resource], method: :delete

表单也是如此:

<%= form_for [:complicated_scope, @my_resource] do |f| %>

如果@my_resource是一个新对象(未持久化(,就像在new操作的情况下一样,这将等效于向/complicated_scope/my_resource 发送post请求,请求正文中带有形式参数。

或者,如果存在@my_resource,例如在edit操作的情况下,上述操作等效于发送一个PUT/PATCH,该将使用/complicated_scope/my_resource/:id/update路由到控制器的update操作。

最新更新