rails 中的表单和嵌套资源

Forms and nested resources in rails

我有 4 个模型用户、客户、发票和项目

目前用户可以点击一个客户并查看该客户的所有发票。但是,当他选择创建新发票时,新发票已分配给客户。我还希望用户能够创建新发票并从列表中选择客户或制作新发票。

路线和模型

devise_for :users
resources :invoices, only: [:new]
resources :clients do
resources :invoices, shallow: true
end

class User < ActiveRecord::Base
has_many :invoices
has_many :clients

class Client < ActiveRecord::Base
has_many :invoices
has_many :items, through: :invoices

class Invoice < ActiveRecord::Base
belongs_to :client
has_many :items, :dependent => :destroy

class Item < ActiveRecord::Base
belongs_to :invoice
belongs_to :client

我将行 resources :invoices, only: [:new] 添加到 routes.rb 文件并将 <%= link_to 'New Invoice', new_invoice_path(@invoice) %> 添加到 aplication.html.erb

但是,我已经将 new 操作设置为仅在 route /clients/:client_id/invoices/new

上创建 invoice 时才起作用

发票控制器

def new
 @client = Client.find(params[:client_id])
 @invoice = @client.invoices.new
end

还有我的表格

<%= simple_form_for [@client, @invoice] do |f| %>

如果我将控制器的新操作更改为

def new
 @invoice = Invoice.new
end

我得到 undefined method invoices_path for # 我知道这是我设置 form

的方式

我怎样才能使两条路线都通过一个控制器动作工作?我应该有 2 个表格吗?

您还需要在路由中启用 :create(其中 form_for 将 link 通过 post 方法)并有一个控制器操作

def create

处理表单的输入。不然不行。