2013-01-20 18 views
0

嘗試使用嵌套屬性以一種形式創建OrganizationUser。我收到以下錯誤:不能大規模指派保護的屬性:用戶(::加載ActiveModel :: MassAssignmentSecurity錯誤)使用accept_nested_attributes_for(b/t&has_many)創建單獨形式的單獨模型

拉我的頭髮就這一個

organization.rb

class Organization < ActiveRecord::Base 
    attr_accessible :name, :users_attributes 
    has_many :users, dependent: :destroy  
    accepts_nested_attributes_for :users 
end 

user.rb(使用色器件)

class User < ActiveRecord::Base 
    attr_accessible :email  
    belongs_to :organization 
end 

new.html.haml

= form_for @organization do |f| 

    = f.label :name, "Company Name" 
    = f.text_field :name, placeholder: "Company Name" 

    = f.fields_for :user do |ff| -# tried :users here and the form doesn't render 
    = ff.label :email, "Email Address" 
    = ff.email_field :email, placeholder: "Email Address" 

= f.submit "Create Account" 

回答

1

這已經回答了很多#2。

f.fields_for :users 

而在控制器,你需要建立一個用戶:

@organization.users.build 

你得到Can't mass-assign protected attributes: user因爲用戶屬性是無法訪問的,因爲它不存在。

+0

感謝您的解釋!我在一個沒有在控制器中的任何地方使用'build'的railscasts上走。我的印象是'accept_nested_attributes'照顧了你的建築物,但我認爲在控制器中顯式構建是有意義的 – pruett