Ruby on rails Rails-销毁嵌套属性的子级
我在绞尽脑汁想弄明白这件事。我有下面的表格,非常好用 你知道我做错了什么吗?这是因为您不能在Rails控制台中执行吗?我需要用表格来代替吗?如果是,我如何以一种形式实现这一点Ruby on rails Rails-销毁嵌套属性的子级,ruby-on-rails,nested-attributes,Ruby On Rails,Nested Attributes,我在绞尽脑汁想弄明白这件事。我有下面的表格,非常好用 你知道我做错了什么吗?这是因为您不能在Rails控制台中执行吗?我需要用表格来代替吗?如果是,我如何以一种形式实现这一点 任何帮助都会很好 指定在销毁父模板时应销毁子模板\u分配: # app/models/template.rb has_many :template_assignments, dependent: :destroy 以下描述了Rails销毁对象的依赖关联所采取的步骤: # from the Rails console &g
任何帮助都会很好 指定在销毁父
模板时应销毁子模板\u分配
:
# 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
从:
有多个、有一个和属于支持:依赖选项的关联。这允许您指定删除所有者时应删除关联的记录
要添加到上述答案中,allow_destroy:true允许您在更新时删除子项,例如,您希望使用一些新的子项更新父项,并删除一些子项。
>> 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.
# app/models/template.rb
has_many :template_assignments, dependent: :destroy
# 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
# app/models/template_assignment.rb
belongs_to :template, dependent: :destroy