在 Sequel 中没有主键的情况下从 table 中删除
Delete from table without primary key in Sequel
我正在尝试删除我刚刚在其 teardown
方法中添加到测试 (minitest) 中的行,它失败并显示 table 没有主键的消息。以下是它的迁移:
Sequel.migration do
up do
create_table :hobbies_users do
Integer :user_id
Integer :hobby_id
unique [:user_id, :hobby_id]
end
end
down do
drop_table :hobbies_users
end
end
我该怎么做?没有主键是不好的做法吗?
测试代码,发现问题所在:
require_relative '../../test_helper.rb'
require 'api/models/users_hobbies'
class UsersHobbiesTest < Minitest::Test
def setup
@uh = UsersHobbies
.new(user_id: User.all.sample.id, hobby_id: Hobby.last.id * 10)
.save
end
def test_accessors
assert_kind_of User, @uh.user
end
def teardown
@uh.destroy
end
end
暂时可以在模型中定义主键:
self.primary_key = :some_column
但我发现有必要在每个 table 中都有主键,因为最近我遇到了一个情况,当我有一个没有主键的关联 table 时,我需要销毁通过删除数据库条目来关联,由于没有主键,这是不可能的(在我的例子中是 MySQL)。
你可以这样做
@record_to_erase = DB["DELETE FROM hobbies_users"]
@record_to_erase.delete
我正在尝试删除我刚刚在其 teardown
方法中添加到测试 (minitest) 中的行,它失败并显示 table 没有主键的消息。以下是它的迁移:
Sequel.migration do
up do
create_table :hobbies_users do
Integer :user_id
Integer :hobby_id
unique [:user_id, :hobby_id]
end
end
down do
drop_table :hobbies_users
end
end
我该怎么做?没有主键是不好的做法吗?
测试代码,发现问题所在:
require_relative '../../test_helper.rb'
require 'api/models/users_hobbies'
class UsersHobbiesTest < Minitest::Test
def setup
@uh = UsersHobbies
.new(user_id: User.all.sample.id, hobby_id: Hobby.last.id * 10)
.save
end
def test_accessors
assert_kind_of User, @uh.user
end
def teardown
@uh.destroy
end
end
暂时可以在模型中定义主键:
self.primary_key = :some_column
但我发现有必要在每个 table 中都有主键,因为最近我遇到了一个情况,当我有一个没有主键的关联 table 时,我需要销毁通过删除数据库条目来关联,由于没有主键,这是不可能的(在我的例子中是 MySQL)。
你可以这样做
@record_to_erase = DB["DELETE FROM hobbies_users"]
@record_to_erase.delete