1

我的问题与 accept_nested_attributes 有关,我有一个模型名称StudentProfile,它包含以下代码:

class StudentProfile < ActiveRecord::Base
   attr_accessible :projects_attributes
   has_many :projects ,:inverse_of => :student_profile,:dependent => :destroy
   accepts_nested_attributes_for :projects, :allow_destroy => true, :reject_if => lambda { |a| a[:name].blank? }
end

我的另一个模型包含以下代码:

class Project < ActiveRecord::Base
   belongs_to :student_profile
end

和我的视图文件包含以下代码:

<%= f.fields_for :projects do |builder| %>
   <%= render "projects_fields", :f => builder %>
<% end %>
<%= link_to_add_fields "Add Project", f, :projects %> 

现在的问题是,每当我保存学生资料时,我实际上也可以保存项目记录,但是每当我尝试更新学生资料并删除其中一个项目时,它实际上并没有在更新时破坏项目,但我params包括以下内容内容:

"projects_attributes"=>{"0"=>{"name"=>"test", "_destroy"=>"1", "id"=>"2"}}

请澄清我做错了什么。

4

1 回答 1

1

可能是批量属性保护,在你的StudentProfile上,添加以下内容:

class StudentProfile < ActiveRecord::Base
  attr_accessible :projects_attributes

  has_many :projects ,:inverse_of => :student_profile,:dependent => :destroy
  accepts_nested_attributes_for :projects, :allow_destroy => true, :reject_if => lambda { |a| a[:name].blank? }
end
于 2013-03-04T10:19:11.577 回答