Rails:违反外键约束

Cod*_*ang 9 ruby ruby-on-rails reference foreign-keys relational-database

我有三个型号:Book,genre,BookGenre,这里有关系:

class BookGenre < ActiveRecord::Base
  belongs_to :book
  belongs_to :genre
end


class Book < ActiveRecord::Base
  has_many :book_genres
  has_many :genres, through: :book_genres
end


class Genre < ActiveRecord::Base
  has_many :book_genres
  has_many :books, through: :book_genres
end
Run Code Online (Sandbox Code Playgroud)

然后我使用seedfile将数据放入这些表中.

但是,当我想再做rake db:seed一次时,它显示了这个错误

ActiveRecord::InvalidForeignKey: PG::ForeignKeyViolation: ERROR:  update or delete on table "books" violates foreign key constraint "fk_rails_4a117802d7" on table "book_genres"
DETAIL:  Key (id)=(10) is still referenced from table "book_genres".
Run Code Online (Sandbox Code Playgroud)

在我的seed.rb

Book.destroy_all
Genre.destroy_all
...create data 
Run Code Online (Sandbox Code Playgroud)

And*_*eko 14

添加dependent: :destroy选项到您的has_many定义.

检查文档

然而,尊重数据完整性的更好选择是设置CASCADE DELETE数据库级别:例如,您有comments表和users表.用户有很多注释你想在表中添加一个foreign_key comments并设置删除注释,每当用户被销毁时你会使用以下内容(该on_delete: :cascade选项将确保它):

add_foreign_key(
  :comments,
  :users,
  column:
  :user_id,
  on_delete: :cascade
)
Run Code Online (Sandbox Code Playgroud)


sco*_*rix 7

试试这个:

ActiveRecord::Base.connection.disable_referential_integrity do
    Book.destroy_all
    Genre.destroy_all
    # ...create data 
end
Run Code Online (Sandbox Code Playgroud)