Ruby on Rails:使用一个表单和一个提交为多个模型创建记录

我有3个型号:报价,客户和项目。 每个报价都有一个客户和一个项目。 当我按下提交按钮时,我想在各自的表格中创建新报价,新客户和新项目。 我已经查看了其他问题和轨道广播,要么它们不适用于我的情况,要么我不知道如何实现它们。

quote.rb

class Quote < ActiveRecord::Base attr_accessible :quote_number has_one :customer has_one :item end 

customer.rb

 class Customer < ActiveRecord::Base attr_accessible :firstname, :lastname #unsure of what to put here #a customer can have multiple quotes, so would i use has_many or belongs_to? belongs_to :quote end 

item.rb的

 class Item < ActiveRecord::Base attr_accessible :name, :description #also unsure about this #each item can also be in multiple quotes belongs_to :quote 

quotes_controller.rb

 class QuotesController < ApplicationController def index @quote = Quote.new @customer = Customer.new @item = item.new end def create @quote = Quote.new(params[:quote]) @quote.save @customer = Customer.new(params[:customer]) @customer.save @item = Item.new(params[:item]) @item.save end end 

items_controller.rb

 class ItemsController < ApplicationController def index end def new @item = Item.new end def create @item = Item.new(params[:item]) @item.save end end 

customers_controller.rb

 class CustomersController < ApplicationController def index end def new @customer = Customer.new end def create @customer = Customer.new(params[:customer]) @customer.save end end 

我的报价单/ new.html.erb

                  

当我尝试提交时,我收到错误:

 Can't mass-assign protected attributes: item, customer 

所以为了尝试修复它我更新了quote.rb中的attr_accessible以包含:item,:customer但是我得到了这个错误:

 Item(#) expected, got ActiveSupport::HashWithIndifferentAccess(#) 

任何帮助将不胜感激。

要提交表单及其关联的子项,您需要使用accepts_nested_attributes_for

要做到这一点,你需要在你将要使用的控制器的模型中声明它(在你的情况下,它看起来像Quote Controller。

 class Quote < ActiveRecord::Base attr_accessible :quote_number has_one :customer has_one :item accepts_nested_attributes_for :customers, :items end 

此外,您需要确保声明哪些属性可访问,以避免其他质量分配错误。

如果你想为不同的模型添加信息,我建议应用nested_model_form,如下所示: http ://railscasts.com/episodes/196-nested-model-form-part-1?view = ascicast。

这个解决方案非常简单和清洁。