使用accepts_nested_attributes_for(b / t& has_many)以单一形式创建单独的模型

时间:2013-01-20 22:58:04

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

尝试使用嵌套属性在一个表单中创建OrganizationUser。我收到以下错误:无法批量分配受保护的属性:user(ActiveModel :: MassAssignmentSecurity :: Error)

把头发拉出来

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 个答案:

答案 0 :(得分:1)

Stackoverflow已经回答了很多。

f.fields_for :users

在控制器中,您需要构建一个用户:

@organization.users.build

您获得Can't mass-assign protected attributes: user因为无法访问用户属性,因为它不存在。