如何修复嵌套字段大量分配受保护属性错误?尽管有attr_accessible

时间:2013-01-08 19:21:58

标签: ruby-on-rails ruby ruby-on-rails-3.2 nested-forms mass-assignment

我有一个属于ParkingCompany或User的地址模型。每个地址可以属于多个用户。但每个ParkingCompany都有一个地址。

我的表单上出现Can't mass-assign protected attributes: addresses错误。这是我的代码

ParkingCompany模特:

class ParkingCompany < ActiveRecord::Base
 attr_accessible :company_id, :description, :email, :telephone, :website, :company_name, :addresses_attributes
 has_many :parking_branch
 has_one :address
 accepts_nested_attributes_for :address
end

地址模型:

class Address < ActiveRecord::Base
  attr_accessible :address1, :address2, :address3, :address_id, :city, :country, :county, :house_name, :postcode, :parking_companies_attributes
  belongs_to :parking_companies
  has_many :users
end

当我尝试通过下面的表单添加新公司时,给我'无法批量分配受保护的属性:地址'错误

我的嵌套表单,new.html.erb:

<h1>New Company</h1>

<%= simple_form_for @parking_company do |f| %>
  <%= f.error_notification %>
  <%= f.input :company_name, :required => true %>
  <%= f.input :email, :required => true %>
  <%= f.input :website %>
  <%= f.input :description, :as => :text, :input_html => { :rows => 3 } %>
  <%= f.input :telephone, :required => false %>
     <%= f.simple_fields_for :addresses do |a| %>
     <%= a.input :address1 %>
     <%= a.input :address2, :required => false %>
     <%= a.input :address3, :required => false %>
     <%= a.input :city %>
     <%= a.input :county %>
     <%= a.input :postcode %>
     <%= a.country_select :country, ["United Kingdom"], { keys: :alpha3s, values: :names } %>
  <% end %><br/>
  <%= f.button :submit, 'Create new company', :class => 'btn-primary' %>
<% end %>

以防万一,这是parking_companies_controller

class ParkingCompaniesController < ApplicationController
  def index
    authorize! :index, @parking_company, :message => 'Not authorized as an administrator.'
    @parking_companies = ParkingCompany.all
  end

  def show
    @parking_company = ParkingCompany.find(params[:id])
  end

  def new
    @parking_company = ParkingCompany.new

  end

  def create
    @parking_company = ParkingCompany.create(params[:parking_company])
  end

  def update
  end

  def destroy
  end
end

1 个答案:

答案 0 :(得分:2)

有一个has_one :address,然后您在表单中引用:addresses