win.joshi
win.joshi

Reputation: 13

Rails 3 form_for and fields_for issue

I have the following model:

class Employee < ActiveRecord::Base
has_many :emp_assignments, :dependent => :destroy, :order => 'created_at DESC'
has_many :active_assignments, :class_name => "EmpAssignment", :conditions=>"end_date is not null or end_date > CURRENT DATE", :order => 'created_at DESC'

Form employees/edit_emp_projects.html.erb

<%= form_for(@employee, :html => {:class => "employee_project_form"}) do |f| %>

  <%= f.fields_for :active_assignments do |eaf| %>
    <%= render 'emp_assignments/form_emp_assnmnt', :eaf=>eaf %>
  <% end %> 

<% end %>

Problem is inside emp_assignments/_form_emp_assnmnt.html.erb:

<%if eaf.object.new_record? %>

  <%= render 'emp_assignments/form_segment', :eaf=>eaf %>

<% else %>

  <%= eaf.hidden_field :product_id %>

<% end %>

Rails complains that eaf.object is nil, failing by saying undefined method new_record? on nil class.

If I change :active_assignments in edit_emp_projects.html.erb to :emp_assignments the problem goes away. What's going wrong when I refer to :active_assignments?

Upvotes: 1

Views: 888

Answers (1)

fl00r
fl00r

Reputation: 83680

You should add accepts_nested_attributes_for into your model:

class Employee < ActiveRecord::Base
  has_many :emp_assignments, :dependent => :destroy, :order => 'created_at DESC'
  has_many :active_assignments, :class_name => "EmpAssignment", :conditions=>"end_date is not null or end_date > CURRENT DATE", :order => 'created_at DESC'
  accepts_nested_attributes_for :active_assignments
end

Upvotes: 1

Related Questions