Rails 3.2 - accepts_nested_attributes_for和视图 - 表单不显示



我必须为用户教师建模。

用户

class User < ActiveRecord::Base
  ...
  has_one :teacher
  accepts_nested_attributes_for :teacher
end

教师

class Teacher < ActiveRecord::Base
  attr_accessible :teacher_last_name
  belongs_to :user
  ...
end

我在controller/views/admins/new_tacher.hmtl.erb中也有表单

<%= form_for @user, :url => create_teacher_url, :html => {:class => "form-horizontal"} do |f| %>
  <%= field_set_tag do %>
    <% f.fields_for :teacher do |builder| %>
      <div class="control-group">
        <%= builder.label :teacher_last_name, "Last name", :class => "control-label" %>
        <div class="controls">
          <%= builder.text_field %>
        </div>
      </div>
    <% end %>
    <%= f.submit "Create", :class => "btn btn-large btn-success" %>
<% end %>

管理员控制器

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

所以,我有两个问题:

  1. 为什么我的表格没有出现
  2. 是<%=builder.text_field%>是否正确

我找到了解决方案。它非常容易修复。在fields_for中,应使用<%=而不是<%。

在我的情况下,我的观点现在看起来像:

<%= form_for @user, :url => create_teacher_url, :html => {:class => "form-horizontal"} do |f| %>
  <%= field_set_tag do %>
        <%= f.fields_for :teacher do |builder| %>
      <div class="control-group">
        <%= builder.label :teacher_last_name, "Last name", :class => "control-label" %>
        <div class="controls">
          <%= builder.text_field :teacher_last_name %>
        </div>
      </div>
  <% end %> 
  <%= f.submit "Create", :class => "btn btn-large btn-success" %>
<% end %>
  1. 你为表单创建了一个新的teacher对象吗?-确保您的控制器中有类似的内容:@user.build_teacher
  2. 否,您需要提供要使用的属性builder.text_field :teacher_last_name

相关内容

  • 没有找到相关文章

最新更新