Sha256: 2de1722295e88bc9cfa84126ab1c9d89f5d974750e2643ccadffd58e1226c634

Contents?: true

Size: 856 Bytes

Versions: 6

Compression:

Stored size: 856 Bytes

Contents

# define composite key and check before save
# class OrgUser < ApplicationModel
#   primary_keys :org_id, :user_id
# end

module Sequel::Plugins::PrimaryKeys
  module ClassMethods
    def primary_keys(*args)
      unless args[0]
        return respond_to?(:_primary_keys) ? _primary_keys : [:id]
      end

      define_singleton_method(:_primary_keys) { args }
    end
  end

  module InstanceMethods
    def before_save
      klass = self.class

      if klass.respond_to?(:_primary_keys)
        check = klass._primary_keys.inject(klass.dataset) do |record, field|
          record = record.where(field =>send(field))
        end

        check = check.xwhere('id<>?', id) if self[:id]

        raise StandardError, 'Record allredy exists (primary_keys check)' if check.first
      end

      super
    end
  end
end

Sequel::Model.plugin :primary_keys

Version data entries

6 entries across 6 versions & 1 rubygems

Version Path
lux-fw-0.5.37 ./plugins/db/helpers/composite_primary_keys.rb
lux-fw-0.5.36 ./plugins/db/helpers/composite_primary_keys.rb
lux-fw-0.5.35 ./plugins/db/helpers/composite_primary_keys.rb
lux-fw-0.5.34 ./plugins/db/helpers/composite_primary_keys.rb
lux-fw-0.5.33 ./plugins/db/helpers/composite_primary_keys.rb
lux-fw-0.5.32 ./plugins/db/helpers/composite_primary_keys.rb