嵌套表单的另一个质量分配错误

时间:2013-04-20 17:36:59

标签: ruby-on-rails nested-forms

我已经完成了10次,每次我遇到嵌套表单的问题。这就是我所拥有的:

客户端控制器:

  def new
    @client = Client.new
    @contact = @client.contacts.new
    @header = "New Client"

    respond_to do |format|
      format.html # new.html.erb
      format.json { render json: @client }
    end
  end

客户端类:

class Client < ActiveRecord::Base
  ## ASSOCIATIONS ##
  belongs_to :user
  has_many :contacts, :dependent => :destroy
  has_many :invoices

  ## ACCESSIBLE ##
  attr_accessible :name, :address_line_one, :address_line_two,
                      :contacts_attributes
  ## NESTED ATTRIBUTES ##
  accepts_nested_attributes_for :contacts

形式:

  = form_for(@client) do |f|
    = f.fields_for(@contact) do |contact|

但提交表单时仍然会出现此错误:

Can't mass-assign protected attributes: contact

和params:

"client"=>{"name"=>"23",
 "contact"=>{"name"=>"asdf",
 "email"=>"af@gmail.com"}},
 "commit"=>"Save"}

1 个答案:

答案 0 :(得分:0)

我要做的是:

def new
  @client = Client.new
  @client.contacts.build
  @header = "New Client"

  respond_to do |format|
    format.html # new.html.erb
    format.json { render json: @client }
  end
end

= form_for(@client) do |f|
  = f.fields_for(:contacts) do |contact|