How do I make nested_attributes work in Rails3?

前提是你 提交于 2019-12-11 10:36:44

问题


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!


回答1:


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!)



来源:https://stackoverflow.com/questions/4525962/how-do-i-make-nested-attributes-work-in-rails3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!