Monday, September 28, 2009

Problem with nested attributes for has one relation in form view

Scenario:

# app/models/teacher.rb
has_one :profile
accepts_nested_attributes_for :profile

# app/controllers/teachers_controller.rb
def new
@teacher = Teacher.new
@teacher.profile = Profile.new
end

If the following view give you error.

# app/views/teachers/_form.html.erb
<% form.fields_for :profile do |profile_form| %>
...
<% end %>

# Error in console
You have a nil object when you didn't expect it!
You might have expected an instance of ActiveRecord::Base.
The error occurred while evaluating nil.new_record? (ActionView::TemplateError)
On line #1 of app/views/teachers/_form.erb

1: <% form.fields_for :profile do |profile_form| %>

Then it means you don't have any fields for parent object

<%= form.text_field :login %>
<% form.fields_for :profile do |profile_form| %>
...
<% end %>

No comments:

Blog Archive