删除rails中的标记时无效的外键

时间:2017-07-10 08:41:29

标签: ruby-on-rails

我正在关注此tutorial。本教程要求我为标签实现destroy函数。

可以创建并显示标签。但是,销毁它们会产生以下错误:

 Parameters: {"authenticity_token"=>"VcYU8FRqn4oBXCv0NKXuO7yKNdI+9fIk46rY1ZwD7cQ8cqi37nZDVwNnWJLcNMWVq4gi3OU3YFDgzdeTRa1XKw==",
 "id"=>"1"}
  Tag Load (0.5ms)  SELECT  "tags".* FROM "tags" WHERE "tags"."id" = ? LIMIT ?  [["id", 1], ["LIMIT", 1]]
   (0.0ms)  begin transaction
  SQL (2.0ms)  DELETE FROM "tags" WHERE "tags"."id" = ?  [["id", 1]]
   (1.0ms)  rollback transaction
Completed 500 Internal Server Error in 10ms (ActiveRecord: 3.5ms)



ActiveRecord::InvalidForeignKey (SQLite3::ConstraintException: FOREIGN KEY constraint failed: DELETE FROM "tags" WHERE "tags"."i
d" = ?):

app/controllers/tags_controller.rb:13:in `destroy

tags_controller.rb

class TagsController < ApplicationController

    def index
        @tags = Tag.all
    end

    def show
        @tag = Tag.find(params[:id])
    end

    def destroy
        @tags = Tag.find(params[:id])
        @tags.destroy
        # Set variable to instance of an object of class Article and call .destroy on it.
    end
end

index.html.erb

<h1>Listing tags</h1>

  <% @tags.each do |tag| %>
    <tr>
      <td><%= tag.name %></td>
      <td><%= link_to 'Show', tag_path(tag) %></td>
      <td><%= link_to 'Delete', tag_path(tag),
              method: :delete,
              data: { confirm: 'Are you sure?' } %></td>
    </tr>
  <% end %>
</table>

我错过了一个步骤还是我输错了?

1 个答案:

答案 0 :(得分:5)

tag与应用程序中的其他实体之间存在外键关系。如果删除了标记,依赖该标记的记录将变为孤立,因此数据库会阻止您破坏参照完整性。

你可以摆脱那种关系(在你的模型文件中,你可能指定了一个你可以删除的has_many关系),或者你可以指定一个dependent: :destroy子句来销毁你所有相关的记录。销毁相关标签。第一个选项不太理想,因为你最终会得到很多带有空值的行,然后你必须清理它们。第二个选项更好,因为您保留了引用完整性(数据库中表之间的关系)。

例如,您的tag.rb文件可能如下所示:

class Tag < ApplicationRecord
  has_many :foos, dependent: :destroy
end

这样,当您从数据库中删除标记时,所有关联的foos也会被破坏,数据库也不会抱怨。阅读AR协会android documentation