属于少数模型的模型的嵌套属性形式

时间:2012-04-04 11:26:11

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

我的模型很少 - 用户教师 TeacherLeader

class User < ActiveRecord::Base                                                              
  attr_accessible ...,
                  :teacher_attributes

  has_one :teacher
  has_one :teacher_leader

  accepts_nested_attributes_for :teacher_leader
end

class Teacher < ActiveRecord::Base
  belongs_to :user                                              
  has_one :teacher_leader
end

class TeacherLeader < ActiveRecord::Base
  belongs_to :user
  belongs_to :teacher
end

我想通过嵌套属性填充 TeacherLeader 。所以,我在控制器中做这些事情:

class TeacherLeadersController < ApplicationController
  ...
  def new
    @user = User.new
    @teacher_leader = @user.build_teacher_leader   

    @teachers_collection = Teacher.all.collect do |t| 
      [ "#{t.teacher_last_name} #{t.teacher_first_name} #{t.teacher_middle_name}", t.id ] 
    end

    @choosen_teacher = @teachers_collection.first.last unless @teachers_collection.empty? 
  end
end

还有这样的观点( new.html.erb ):

<%= form_for @user, :url => teacher_leaders_url, :html => {:class => "form-horizontal"} do |f| %>
 <%= field_set_tag do %>
   <% f.fields_for :teacher_leader do |tl| %>
     <div class="control-group">
        <%= tl.label :teacher_id, "Teacher names", :class => "control-label" %>
        <div class="controls">
              <%= select_tag( :teacher_id, 
                  options_for_select( @teachers_collection, @choosen_teacher )) %>           
        </div>
     </div>
   <% end %>
 <% end %> 

     ...    

 <%= f.submit "Create", :class => "btn btn-large btn-success" %>
<% end %>   

问题是这里没有出现选择表格。为什么?我做错了吗?

1 个答案:

答案 0 :(得分:1)

<%= f.fields_for :teacher_leader do |tl| %>