【问题标题】:Creating separate models in single form with accepts_nested_attributes_for (b/t & has_many)使用 accept_nested_attributes_for (b/t & has_many) 以单一形式创建单独的模型
【发布时间】:2013-01-04 00:22:54
【问题描述】:

尝试使用嵌套属性以一种形式创建OrganizationUser。我收到以下错误:Can't mass-assign protected attributes: 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"

【问题讨论】:

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


    【解决方案1】:

    这在 Stackoverflow 上得到了很多回答。

    f.fields_for :users
    

    而在控制器中,你需要建立一个用户:

    @organization.users.build
    

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

    【讨论】:

    • 感谢您的解释!我离开了一个他没有在控制器中的任何地方使用build的railscasts。我的印象是accepts_nested_attributes 为您处理了建筑物,但我想在控制器中显式构建是有意义的
    猜你喜欢
    • 2011-10-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-26
    • 2021-12-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多