Module: Sequel::Plugins::AssociationProxies

Defined in:


Sequel by default does not use proxies for associations. The association method for *_to_many associations returns an array, and the association_dataset method returns a dataset. This plugin makes the association method return a proxy that will load the association and call a method on the association array if sent an array method, and otherwise send the method to the association’s dataset.

You can override which methods to forward to the dataset by passing a block to the plugin:

plugin :association_proxies do |opts|
  [:find, :where, :create].include?(opts[:method])

If the block returns false or nil, the method is sent to the array of associated objects. Otherwise, the method is sent to the association dataset. Here are the entries in the hash passed to the block:


The name of the method


The arguments to the method


The block given to the method


The model instance related to the call


The reflection for the association related to the call


The argument given to the association method call


The block given to the association method call

For example, in a call like:

artist.albums(1){|ds| ds}.foo(2){|x| 3}

The opts passed to the block would be:

  :method => :foo,
  :arguments => [2],
  :block => {|x| 3},
  :instance => artist,
  :reflection => AssociationReflection instance,
  :proxy_argument => 1,
  :proxy_block => {|ds| ds}


# Use association proxies in all model subclasses (called before loading subclasses)
Sequel::Model.plugin :association_proxies

# Use association proxies in a specific model subclass
Album.plugin :association_proxies

Defined Under Namespace

Modules: ClassMethods Classes: AssociationProxy

Class Method Summary collapse

Class Method Details

.configure(model, &block) ⇒ Object

# File 'lib/sequel/plugins/association_proxies.rb', line 53

def self.configure(model, &block)
  model.instance_exec do
    @association_proxy_to_dataset = block if block
    @association_proxy_to_dataset ||= AssociationProxy::DEFAULT_PROXY_TO_DATASET