Module: Sequel::Plugins::DatasetAssociations

Defined in:
lib/sequel/plugins/dataset_associations.rb

Overview

DatasetAssociations allows you to easily use your model associations via datasets. For each association you define, it creates a dataset method for that association that returns a dataset of all objects that are associated to objects in the current dataset. Here’s a simple example:

class Artist < Sequel::Model
  plugin :dataset_associations
  one_to_many :albums
end
Artist.filter(id=>1..100).albums
# SELECT * FROM albums
# WHERE (albums.artist_id IN (
#   SELECT id FROM artists
#   WHERE ((id >= 1) AND (id <= 100))))

This works for all of the association types that ship with Sequel, including the many_through_many type. Most association options that are supported when eager loading are supported when using a dataset association. However, associations that use :limit or one_to_one associations that are really one_to_many relationships in the database will not work correctly, returning all associated objects.

As the dataset methods return datasets, you can easily chain the methods to get associated datasets of associated datasets:

Artist.filter(id=>1..100).albums.filter{name < 'M'}.tags
# SELECT tags.* FROM tags
# WHERE (tags.id IN (
#   SELECT albums_tags.tag_id FROM albums
#   INNER JOIN albums_tags
#     ON (albums_tags.album_id = albums.id)
#   WHERE
#     ((albums.artist_id IN (
#       SELECT id FROM artists
#       WHERE ((id >= 1) AND (id <= 100)))
#     AND
#     (name < 'M')))))

Usage:

# Make all model subclasses create association methods for datasets
Sequel::Model.plugin :dataset_associations

# Make the Album class create association methods for datasets
Album.plugin :dataset_associations

Defined Under Namespace

Modules: ClassMethods, DatasetMethods