module Sequel::Plugins::AssociationPks::InstanceMethods

Public Instance Methods

after_save() click to toggle source

After creating an object, if there are any saved association pks, call the related association pks setters.

Calls superclass method
# File lib/sequel/plugins/association_pks.rb, line 180
def after_save
  if assoc_pks = @_association_pks
    assoc_pks.each do |name, pks|
      instance_exec(pks, &model.association_reflection(name)[:pks_setter])
    end
    @_association_pks = nil
  end
  super
end
refresh() click to toggle source

Clear the associated pks if explicitly refreshing.

Calls superclass method
# File lib/sequel/plugins/association_pks.rb, line 191
def refresh
  @_association_pks = nil
  super
end

Private Instance Methods

_association_pks_getter(opts) click to toggle source

Return the primary keys of the associated objects. If the receiver is a new object, return any saved pks, or an empty array if no pks have been saved.

# File lib/sequel/plugins/association_pks.rb, line 201
def _association_pks_getter(opts)
  delay = opts.fetch(:delay_pks, true)
  if new? && delay
    (@_association_pks ||= {})[opts[:name]] ||= []
  elsif delay && @_association_pks && (objs = @_association_pks[opts[:name]])
    objs
  else
    instance_exec(&opts[:pks_getter])
  end
end
_association_pks_setter(opts, pks) click to toggle source

Update which objects are associated to the receiver. If the receiver is a new object, save the pks so the update can happen after the receiver has been saved.

# File lib/sequel/plugins/association_pks.rb, line 215
def _association_pks_setter(opts, pks)
  if pks.nil?
    case opts[:association_pks_nil]
    when :remove
      pks = []
    when :ignore
      return
    else
      raise Error, "nil value given to association_pks setter"
    end
  end

  pks = convert_pk_array(opts, pks)

  if opts.fetch(:delay_pks, true)
    modified!
    (@_association_pks ||= {})[opts[:name]] = pks
  else
    instance_exec(pks, &opts[:pks_setter])
  end
end
convert_pk_array(opts, pks) click to toggle source

If the associated class's primary key column type is integer, typecast all provided values to integer before using them.

# File lib/sequel/plugins/association_pks.rb, line 239
def convert_pk_array(opts, pks)
  klass = opts.associated_class
  primary_key = klass.primary_key
  sch = klass.db_schema

  if primary_key.is_a?(Array)
    if (cols = sch.values_at(*klass.primary_key)).all? && (convs = cols.map{|c| c[:type] == :integer}).all?
      pks.map do |cpk|
        cpk.zip(convs).map do |pk, conv|
          conv ? model.db.typecast_value(:integer, pk) : pk
        end
      end
    else
      pks
    end
  elsif (col = sch[klass.primary_key]) && (col[:type] == :integer)
    pks.map{|pk| model.db.typecast_value(:integer, pk)}
  else
    pks
  end
end