Rails - 销毁嵌套属性的子项

时间:2013-09-24 21:19:28

标签: ruby-on-rails nested-attributes

我正试图弄清楚这一点。我有以下表格,其中很好

  <%= bootstrap_form_for @template do |f| %>
     <%= f.text_field :prompt, :class => :span6, :placeholder => "Which one is running?", :autocomplete => :off %>
     <%= f.select 'group_id', options_from_collection_for_select(@groups, 'id', 'name') %>
     <% 4.times do |num| %>
        <%= f.fields_for :template_assignments do |builder| %>
            <%= builder.hidden_field :choice_id %>
            <%= builder.check_box :correct %>
        <% end %>
      <% end %>
   <% end %>

然后我有我的模特:

  class Template < ActiveRecord::Base
   belongs_to :group
   has_many :template_assignments
   has_many :choices, :through => :template_assignments
   accepts_nested_attributes_for :template_assignments, :reject_if => lambda { |a| a[:choice_id].blank? }, allow_destroy: true
  end

提交表单后,嵌套属性将精美地添加。但是,当我想删除一个模板时,我也希望它删除所有子项“template_assignments”,这就是我假设的“allow_destroy =&gt; true”

所以,我是从Rails控制台尝试这个(这可能是我的问题?)我会做类似的事情:

 >> t = Template.find(1)
 #Which then finds the correct template, and I can even type: 
 >> t.template_assignments
 #Which then displays the nested attributes no problem, but then I try: 
 >> t.destroy
 #And it only destroys the main parent, and none of those nested columns in the TemplateAssignment Model.

我在这里做错了什么想法?是因为你不能在Rails控制台中这样做吗?我需要在表单中进行吗?如果是这样,我如何以表格形式实现这一目标?

任何帮助都会很棒!

1 个答案:

答案 0 :(得分:6)

指定在销毁父template_assignments时销毁子Template

# app/models/template.rb
has_many :template_assignments, dependent: :destroy

下面描述了Rails用于销毁对象依赖关联的步骤:

# from the Rails console
>>  t = Template.find(1)
#=> #<Template id:1>
>>  t.template_assignments.first
#=> #<TemplateAssignment id:1>
>>  t.destroy
#=> SELECT "template_assignments".* FROM "template_assignments" WHERE "template_assignments"."template_id" = 1
#=> DELETE FROM "template_assignments" WHERE "template_assignments"."id" = ?  [["id", 1]]
>>  TemplateAssignment.find(1)
#=> ActiveRecord::RecordNotFound: Couldn't find TemplateAssignment with id=1

可以在关联的任一侧指定:dependent选项,因此可以在子关联上声明,而不是父关联:

# app/models/template_assignment.rb
belongs_to :template, dependent: :destroy

来自Rails docs

  

has_many,has_one和belongs_to关联支持:dependent选项。这允许您指定在删除所有者时删除关联的记录