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

时间:2013-06-26 21:33:07

标签: ruby-on-rails forms models

我有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

<%= form_for @quote do |f| %>
  <%= f.fields_for @customer do |builder| %>
    <%= label_tag :firstname %>
    <%= builder.text_field :firstname %>
    <%= label_tag :lastname %>
    <%= builder.text_field :lastname %>
  <% end %>
  <%= f.fields_for @item do |builder| %>
    <%= label_tag :name %>
    <%= builder.text_field :name %>
    <%= label_tag :description %>
    <%= builder.text_field :description %>
  <% end %>
  <%= label_tag :quote_number %>
  <%= f.text_field :quote_number %>
  <%= f.submit %>
<% end %>

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

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

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

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

非常感谢任何帮助。

2 个答案:

答案 0 :(得分:4)

要提交表单及其关联的孩子,您需要使用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

此外,您需要确保声明哪个attributes are accessible,以避免其他质量分配错误。

答案 1 :(得分:1)

如果您想为不同的模型添加信息,我建议您应用嵌套模型表单,例如:http://railscasts.com/episodes/196-nested-model-form-part-1?view=asciicast

这个解决方案非常简单,最简洁。

相关问题