Rails 3 form_for和fields_for issue

时间:2011-07-13 16:01:20

标签: ruby-on-rails-3

我有以下型号:

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'

表格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 %>

问题出在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抱怨说eaf.object是nil,没说未定义的方法new_record?在零级。

如果我将edit_emp_projects.html.erb中的active_assignments更改为:emp_assignments,则问题就会消失。当我提到:active_assignments?

时会出现什么问题

1 个答案:

答案 0 :(得分:1)

您应该将accepts_nested_attributes_for添加到模型中:

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