加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – 嵌套表单 – 无法批量分配受保护的属性

发布时间:2020-12-17 02:20:45 所属栏目:百科 来源:网络整理
导读:我有点难过这个,因为我觉得我已经躲过了常见的错误(比如 mistyping the attr_accessible或 leaving it out altogether),但我还是得到了一个 Can't mass-assign protected attributes: home,work 错误在这里.我猜我错过了什么,但我不确定是什么. 无论如何,在
我有点难过这个,因为我觉得我已经躲过了常见的错误(比如 mistyping the attr_accessible或 leaving it out altogether),但我还是得到了一个

Can't mass-assign protected attributes: home,work

错误在这里.我猜我错过了什么,但我不确定是什么.

无论如何,在我的新应用中,用户有一个Home和一个Work(每个都属于一个用户),我希望用户在注册时输入它们.所以,在我的模特中:

user.rb

attr_accessible :email,:first_name,:last_name,:password,:password_confirmation,:home_attributes,:work_attributes

  has_one :home,:work

  accepts_nested_attributes_for :work,:home

  has_secure_password

home.rb

attr_accessible :address,:latitude,:longitude,:user_id
belongs_to :user

validates :address,presence: true

work.rb

attr_accessible :address,presence: true

在我的控制器中

users_controller.rb

def new
    @user = User.new

  respond_to do |format|
    format.html # new.html.erb
    format.json { redirect_to @user }
  end
end

并以我的形式:

意见/用户/ _form.html.haml

= form_for @user do |f|
  - if @user.errors.any?
    .error_explanation
      %h2
        = pluralize(@user.errors.count,"error") 
        prohibited this post from being saved:
      %ul
        - @user.errors.full_messages.each do |msg|
          %li= msg

  = f.label :first_name
  = f.text_field :first_name

  = f.label :last_name
  = f.text_field :last_name

  = f.label :email
  = f.text_field :email

  = f.label :password
  = f.password_field :password

  = f.label :password_confirmation,"Re-Enter Password"
  = f.password_field :password_confirmation

  = f.fields_for :home do |builder|
    = builder.label :address,"Home address"
    = builder.text_field :address
  %br
  = f.fields_for :work do |builder|
    = builder.label :address,"Work address"
    = builder.text_field :address

  .btn-group
    = f.submit 'Sign Up!',class: "btn"

解决方法

看起来您没有设置实例变量来包含这些属性.

在你的控制器中你应该有这样的东西

def new
    @user = User.new
    @user.homes.build
    @user.works.build

  respond_to do |format|
    format.html # new.html.erb
    format.json { redirect_to @user }
  end
end

如果您不构建这些属性,则表单不知道该怎么做.

编辑:修复了构建嵌套资源的语法

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读