【问题标题】:Forms and nested resources in railsRails 中的表单和嵌套资源
【发布时间】: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 文件和&lt;%= link_to 'New Invoice', new_invoice_path(@invoice) %&gt;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


【解决方案1】:

您还需要在路由中启用 :create(form_for 将通过 post 方法链接到该位置)并具有控制器操作

def create

处理表单的输入。否则将无法正常工作。

【讨论】:

  • 谢谢,我在路线中添加了resources :invoices, only: [:new, :create],并将表单更改为&lt;%= simple_form_for (@invoice) do |f| %&gt;,它按预期工作
猜你喜欢
  • 1970-01-01
  • 2014-08-02
  • 1970-01-01
  • 2015-09-30
  • 1970-01-01
  • 2012-02-02
  • 2012-02-09
  • 2014-04-07
  • 2015-01-05
相关资源
最近更新 更多