从索引创建嵌套资源的新记录

时间:2017-07-18 23:53:17

标签: ruby-on-rails ruby

我有2个嵌套资源:

  resources :clientes do
    resources :projects
  end

我的索引页面上需要2个按钮,一个用于创建客户端,另一个用于创建项目。

<%= link_to "Nuevo Cliente", new_cliente_path %>
<%= link_to "Nuevo Projecto", new_cliente_project_path() %>

问题: 单击新项目时, new_cliente_project_path 需要在参数中传递的客户端ID。

我仍然没有该参数,因为要创建的新项目尚未分配客户端。

我希望从新项目表单中选择项目的客户端。

我该怎么办?

谢谢!

1 个答案:

答案 0 :(得分:1)

您需要拥有一个非嵌套资源,例如:

resources :clientes do
  resources :projects, except: [:new, :create]
end

resources :projects, only: [:new, :create]

会给你(注意你的new_projectsprojects路径将不再需要cliente_id):

    cliente_projects GET    /clientes/:cliente_id/projects(.:format)              projects#index
edit_cliente_project GET    /clientes/:cliente_id/projects/:id/edit(.:format)     projects#edit
     cliente_project GET    /clientes/:cliente_id/projects/:id(.:format)          projects#show
                     PATCH  /clientes/:cliente_id/projects/:id(.:format)          projects#update
                     PUT    /clientes/:cliente_id/projects/:id(.:format)          projects#update
                     DELETE /clientes/:cliente_id/projects/:id(.:format)          projects#destroy
            clientes GET    /clientes(.:format)                                   clientes#index
                     POST   /clientes(.:format)                                   clientes#create
         new_cliente GET    /clientes/new(.:format)                               clientes#new
        edit_cliente GET    /clientes/:id/edit(.:format)                          clientes#edit
             cliente GET    /clientes/:id(.:format)                               clientes#show
                     PATCH  /clientes/:id(.:format)                               clientes#update
                     PUT    /clientes/:id(.:format)                               clientes#update
                     DELETE /clientes/:id(.:format)                               clientes#destroy
            projects POST   /projects(.:format)                                   projects#create
         new_project GET    /projects/new(.:format)                               projects#new

然后,而不是:

<%= link_to "Nuevo Projecto", new_cliente_project_path() %>

您需要执行以下操作:

<%= link_to "Nuevo Projecto", new_project_path %>

在您的新项目表单中,您需要选择客户或类似的内容,因此当您提交表单时,您可以使用client_id来创建关联。