Question

I have to models, User and Teacher.

User

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

Teacher

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

I also have form in controllers/views/admins/new_teacher.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 %>

Admin controller

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

So, i have 2 questions:

  1. Why is my form not appear?
  2. Is <%= builder.text_field %> correct?
Was it helpful?

Solution

I found solution. It's amazing easy to fix. In fields_for you should use <%= instead of <%.

In my case my view now looks like:

<%= 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 %>

OTHER TIPS

  1. Have you built a new teacher object for the form to use? - Ensure you have something like this in your controller: @user.build_teacher
  2. No, you need to provide the attribute you want to use, builder.text_field :teacher_last_name
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top