Search code examples
rubyminitestsequel

Delete from table without primary key in Sequel


I am trying to delete a row I just added in a test (minitest) in its teardown method & it fails with the message that the table doesn't have a primary key. Following is its migration:

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

How can I do it? Is it bad practice not to have a primary key?

Test code, where I found the problem:

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

Solution

  • For the time being you can define primary key in model:

    self.primary_key = :some_column
    

    But I find it necessary to have primary keys in every table, because lately I faced a situation, when I was having an association table without a primary key, and I needed to destroy the association by deleting the db entry, which was impossible due to absence of primary key (in my case it was MySQL).