0

所以我有两个模型,报告和收据。每份报告都有许多收据。我使用脚手架来生成我所有的视图和东西,但我改变了一些东西,以便当用户创建新报告或编辑报告时,他们可以在表单中创建和编辑收据。

我的模型设置:

class Report < ActiveRecord::Base

    has_many :receipts, :dependent => :destroy
  accepts_nested_attributes_for :receipts, :allow_destroy => true

    attr_protected :id

end
class Receipt < ActiveRecord::Base
    belongs_to :report

    attr_protected :id

    validates_presence_of :vendor, :date, :description, :amount, :acctCode
end

我已设置表单以创建新收据:

    <%= form_for @report do |f| %>
     ....
       <%= f.fields_for :receipts, Receipt.new do |receipt| %>
       ...
       <% end %>
    <% end %>

但是每次我去保存报告时,都会出现路由错误:

No route matches {:action=>"edit", :controller=>"receipts", :report_id=>#<Receipt id: nil, date: nil, vendor: "", description: "", amount: nil, companyCard: false, lobbyingExpense: false, acctCode: "", created_at: nil, updated_at: nil, report_id: 2>}

我的路线设置为:

resources :reports do
    resources :receipts
end

我的收据控制器有

  # GET /receipts/new
  def new
    @receipt = Receipt.new

    respond_to do |format|
      format.html # new.html.erb
    end
  end

  # GET /receipts/1/edit
  def edit
    @receipt = Receipt.find(params[:id])
  end

  # POST /receipts
  def create
    @receipt = Receipt.new(params[:receipt])

    respond_to do |format|
      if @receipt.save
        format.html { redirect_to @receipt.Report, notice: 'Receipt was successfully created.' }
      else
        format.html { render action: "new" }
      end
    end
  end

我有一段时间没碰过铁轨了,所以我不知道我做错了什么。但是在我的旧应用程序 (3.1) 中,当我添加图像来表示博客文章时,我什至没有图像控制器,除了通过 ajax 删除它们。我在这里有一个收据控制器的唯一原因是因为我使用脚手架来生成视图等。

编辑 - 我还应该指出,如果我转到新的收据视图,我会在表单标签上收到一个错误:

<%= form_for(@receipt) do |receipt| %>

undefined method `receipts_path'
4

2 回答 2

1

如果您正在使用accepts_nested_attributes_for,则不需要额外的控制器来管理记录。当然,如果您需要特定页面,例如收据的“显示视图”,则需要该控制器。

为了得到accepts_nested_attributes_for你需要:

  1. 报告表格
  2. fields_for :receipts以那种形式使用

这样,您可以编辑给定报告的所有已创建收据。如果您还想创建新收据,您可以使用以下命令添加空白收据:@report.receipts.build。您可以将此调用添加到您的newedit操作中。

请注意,您在报表的表单中编辑收据。这意味着,您应该点击ReportsController而不是ReceiptsController.

如果事情在这里不起作用,请提供一些调试建议:

  • 执行 rake routes 以查看是否所有内容都已正确定义。
  • 检查生成的 HTML 来自form_for(@report). 尤其是表单标签的 'action=""' 属性是相关的。它应该指向“/reports/X”

编辑:我创建了一个包含所有相关文件的 Gist 以使嵌套表单工作:https ://gist.github.com/4420280

于 2012-12-31T14:37:17.727 回答
0

为嵌套资源表单结帐茧宝石。这个 gem 使处理嵌套资源的工作变得更加容易。https://github.com/nathanvda/cocoon

于 2013-01-03T19:26:00.690 回答