gpt4 book ai didi

ruby-on-rails - 嵌套表单 - 无法批量分配 protected 属性

转载 作者:行者123 更新时间:2023-12-04 18:47:08 24 4
gpt4 key购买 nike

我有点被这个难住了,因为我觉得我已经避开了常见的错误(比如 mistyping the attr_accessibleleaving it out altogether ),但我仍然得到一个

Can't mass-assign protected attributes: 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, :latitude, :longitude, :user_id
belongs_to :user

validates :address, presence: true

在我的 Controller 中

users_controller.rb
def new
@user = User.new

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

并以我的形式:

View /用户/_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"

最佳答案

看起来您尚未设置实例变量以包含这些属性。

在你的 Controller 中你应该有这样的东西

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

如果您不构建这些属性,表单将不知道该做什么。

编辑 :建立嵌套的资源固定的语法

关于ruby-on-rails - 嵌套表单 - 无法批量分配 protected 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15581956/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com