我必须为用户和教师建模。
用户
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
所以,我有两个问题:
- 为什么我的表格没有出现
- 是<%=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 %>
- 你为表单创建了一个新的
teacher
对象吗?-确保您的控制器中有类似的内容:@user.build_teacher
- 否,您需要提供要使用的属性
builder.text_field :teacher_last_name