我有點難住這一個,因爲我覺得我躲過了常見的錯誤(如mistyping the attr_accessible或leaving 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
在我的控制器
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"
這是奇怪的,我認爲錯誤是說,它不能分配'home'當真正的參數應該被命名爲'home_attributes'。你有沒有嘗試在你的新動作中執行'@ user.build_home'和'@ user.build_work'設置? – awbergs 2013-03-23 01:31:47
我嘗試添加這兩條線 - 「@Home = Home.new」 和 「@Work = Work.new」 - 在我的控制器,然後做 「f.fields_for @Home做|製造商|」。你是這個意思嗎?這種抗議類似。 – Sasha 2013-03-23 01:46:21
否定的。你要專門建立它爲您@user對象('@ user.build_home','@ user.build_work') – awbergs 2013-03-23 01:48:10