我正在使用数据库清理器与续集和sqlite外键约束遇到问题.具体来说,我正在使用:truncation
Capybara集成测试的策略.
对于给定的示例模式:
CREATE TABLE users(id INTEGER PRIMARY KEY, name TEXT);
CREATE TABLE events(id INTEGER PRIMARY KEY, title TEXT);
CREATE TABLE events_users(
user_id INTEGER,
event_id INTEGER,
FOREIGN KEY(user_id) REFERENCES users(id),
FOREIGN KEY(event_id) REFERENCES events(id)
);
和续集模特:
class User < Sequel::Model
many_to_many :events
end
class Event < Sequel::Model
many_to_many :users
end
运行以下内容:
# normally this would be run in # an rspec before(:each) for my :feature specs DatabaseCleaner.start DatabaseCleaner.strategy = :truncation bob = User.create(name: "bob") sally = User.create(name: "sally") event = Event.create(title: "Everyone's invited") event.users << [bob, sally] DatabaseCleaner.clean
导致错误
SQLite3::ConstraintException: FOREIGN KEY constraint failed (Sequel::ForeignKeyConstraintViolation)
我可以通过改变我的before语句来禁用foreign_keys PRAGMA来解决这个问题:
DB.foreign_keys = false DatabaseCleaner.start DatabaseCleaner.strategy = :truncation
(或者在我的表中没有使用FOREIGN KEY),但这似乎是错的,因为我想要外键约束的好处 - 或者至少我认为我做的;).
这是对如何使用外键约束的基本误解,还是有更好的方法来做到这一点?