【发布时间】:2016-03-16 23:27:00
【问题描述】:
我有 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 个表格吗?
【问题讨论】:
-
您没有显示发票路径所在的代码...运行
rake routes并确保这是发票的正确助手...因为您嵌套了很可能不是的路线。 -
嵌套资源块外的
resources :invoices, only: [:new]行创建路由 new_invoice GET /invoices/new(.:format) -
但错误是未定义的方法
invoices_path!这就是添加创建固定的原因。
标签: ruby-on-rails forms nested-resources