Search code examples
rubyactiverecordmigrationassociationssequel

How is the following Rails model should look like in Sequel?


I've the following two models:

class Dispute < ApplicationRecord
  belongs_to :accuser,    class_name: 'User', optional: true
  belongs_to :defendant,  class_name: 'User', optional: true
end
class User < ApplicationRecord
end

Here's the migration for Dispute:

class CreateDisputes < ActiveRecord::Migration[5.0]
  def change
    create_table :disputes do |t|
      t.references :accuser
      t.references :defendant
    end
  end
end

This is how they behave in Rails:

Dispute.first.accuser
# => <# User>
Dispute.first.defendant
# => <# User>

In Sequel, I'm supposed to use many_to_one, but does that mean that Sequel User model should have a corresponding one_to_many? Can't seem to get it to work.


Solution

  • This should work:

    Sequel.migration do
      change do
        create_table(:disputes) do
          primary_key :id
          foreign_key :accuser_id, :users
          foreign_key :defendant_id, :users
        end
      end
    end
    
    class Dispute < Sequel::Model
      many_to_one :accuser, :class=>:User
      many_to_one :defendant, :class=>:User
    end