2

我正在努力解决这个问题。我有以下表格,效果很好

  <%= 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 => 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 控制台中执行此操作吗?我需要用表格代替吗?如果是这样,我如何以一种形式实现这一点?

任何帮助都会很棒!

4

1 回答 1

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 文档

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

于 2013-09-24T21:24:27.437 回答