Rails - 销毁嵌套属性的子项

Dod*_*nas 2 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 %>
Run Code Online (Sandbox Code Playgroud)

然后我有我的模型:

  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
Run Code Online (Sandbox Code Playgroud)

提交表单时,嵌套属性会很好地添加.但是,当我想删除一个模板时,我也希望它删除所有子项"template_assignments",这就是我假设的"allow_destroy => 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.
Run Code Online (Sandbox Code Playgroud)

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

任何帮助都会很棒!

zea*_*soi 6

指定template_assignments在销毁父项时应销毁该子项Template:

# app/models/template.rb
has_many :template_assignments, dependent: :destroy
Run Code Online (Sandbox Code Playgroud)

下面描述了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
Run Code Online (Sandbox Code Playgroud)

:dependent选项可以在协会的两侧指定,因此它可以交替地宣布对孩子的关联,而不是父:

# app/models/template_assignment.rb
belongs_to :template, dependent: :destroy
Run Code Online (Sandbox Code Playgroud)

来自Rails文档:

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