Rails 3 - 通过嵌套属性保存几个彼此属于的模型

时间:2012-03-21 19:20:24

标签: ruby-on-rails ruby nested-attributes

我无法理解如何做一件事。我有模型用户教师教师教育教师教育属于教师教师属于用户。我希望在我的控制器中通过user.save用户教师教师教育保存在一行中。那可能吗?如果没有那么哪个更好的方法来保存呢?

class User < ActiveRecord::Base
  attr_accessible ...,
                  :teacher_attributes
  has_one :teacher
  accepts_nested_attributes_for :teacher 
end

class Teacher < ActiveRecord::Base
  belongs_to :user 
  has_one :teacher_education
  accepts_nested_attributes_for :teacher_education
end

class TeacherEducation < ActiveRecord::Base
  belongs_to :teacher
end

现在没有TeacherEducation,我有这样的观点

<%= form_for @user, :url => create_teacher_url, :html => {:class => "form-horizontal"} do |f| %>
  <%= field_set_tag do %>
    <%= f.fields_for :teacher do |builder| %>
    # Fields of teacher
    <% end %>
    # Fields of user
<% end %>

我的控制器

class AdminsController < ApplicationController
  def new_teacher
    @user = User.new
    teacher = @user.build_teacher
    ...
  end

  def create_teacher   
    user = User.new( params[:user] )

    if user.save
    ...
    end
  end
end

1 个答案:

答案 0 :(得分:1)

这应该有用,我想..

<%= form_for @user, :url => create_teacher_url, :html => {:class => "form-horizontal"} do |f| %>
  <%= field_set_tag do %>
    <%= f.fields_for :teacher do |builder| %>
      # Fields of teacher
      <%= builder.fields_for :teacher_education do |edu_fields| %>
        # Fields of teacher_education
      <% end %>
    <% end %>
    # Fields of user
<% end %>