我如何使nested_attributes在Rails3中工作? [英] How do I make nested_attributes work in Rails3?
问题描述
以下是我的用户模型:
class User< ActiveRecord :: Base
has_one:teacher,:dependent => :销毁
accept_nested_attributes_for:teacher,:allow_destroy => true
attr_accessible:email,:password,:password_confirmation,:remember_me,:teacher_attributes
end
这是我的老师模型:
class Teacher< ActiveRecord :: Base
belongs_to:user
attr_accessible:user_id,:first_name,:last_name
validates_presence_of:user_id,:first_name,:last_name
end
$ c
这是我的表单:
< ;%= form_for(@user,:url => registration_path(:user))do | user | %GT;
<%= user.text_field:email%>
<%= user.text_field:password%>
<%= user.text_field:password_confirmation%>
<%= user.fields_for resource.build_teacher do | t | %GT;
<%= t.text_field:first_name%>
<%= t.text_field:last_name%>
<%= t.text_field:phone%>
<%end%>
<%= user.submit'确认'%>
<%end%>
除了这个东西不会接受嵌套属性
我的开发日志说:
警告:无法批量分配受保护的属性:teacher
我不知道它是否相关,但表单不是在teacher_attributes数组或其他任何内部生成字段 - 而是在教师内部。我猜这就是我的问题所在,但我不知道如何将它放在里面。请帮助。
谢谢! 试试这些东西:
在视图顶部:
<%@ user.build_teacher如果@ user.teacher.nil? %GT;
以下字段:
<%= user.fields_for:teacher do | t | %GT;
另外,我个人喜欢用表单命名块参数( (因为当你''c $ c> c | c | c | c | c | c | c | c | c | c | c | c |重新过了很长的一天,并且你在视图中看到 user
而不是 form
,它会让你感到困惑!)
Here's my user model:
class User < ActiveRecord::Base
has_one :teacher, :dependent => :destroy
accepts_nested_attributes_for :teacher, :allow_destroy => true
attr_accessible :email, :password, :password_confirmation, :remember_me, :teacher_attributes
end
Here's my teacher model:
class Teacher < ActiveRecord::Base
belongs_to :user
attr_accessible :user_id, :first_name, :last_name
validates_presence_of :user_id, :first_name, :last_name
end
Here's my form:
<%= form_for(@user, :url => registration_path(:user)) do |user| %>
<%= user.text_field :email %>
<%= user.text_field :password %>
<%= user.text_field :password_confirmation %>
<%= user.fields_for resource.build_teacher do |t| %>
<%= t.text_field :first_name %>
<%= t.text_field :last_name %>
<%= t.text_field :phone %>
<% end %>
<%= user.submit 'Confirm' %>
<% end %>
Except that this thing won't "accept nested attributes"
My development log says:
WARNING: Can't mass-assign protected attributes: teacher
I don't know if it's related, but the form isn't generating fields inside a teacher_attributes array or anything - it's inside teacher. I'm guessing that's where my problem is, but I don't how to make it put the fields inside it. Please help.
Thanks!
解决方案 Try these things:
At top of view:
<% @user.build_teacher if @user.teacher.nil? %>
For the fields for:
<%= user.fields_for :teacher do |t| %>
Also, personally, I like naming the block parameters in forms (the part |user|
and |t|
) as |form|
(because when you're having a long day, and you see user
down in the view and not form
, it can confuse you!)
这篇关于我如何使nested_attributes在Rails3中工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!