Module | Sequel::Model::Associations::ClassMethods
In: | lib/sequel/model/associations.rb

Each kind of association adds a number of instance methods to the model class which are specialized according to the association type and optional parameters given in the definition. Example:

      class Project < Sequel::Model
        many_to_one :portfolio
        # or: one_to_one :portfolio
        one_to_many :milestones
        # or: many_to_many :milestones
      end

The project class now has the following instance methods:

portfolio : | Returns the associated portfolio.
portfolio=(obj) : | Sets the associated portfolio to the object, but the change is not persisted until you save the record (for many_to_one associations).
portfolio_dataset : | Returns a dataset that would return the associated portfolio, only useful in fairly specific circumstances.
milestones : | Returns an array of associated milestones
add_milestone(obj) : | Associates the passed milestone with this object.
remove_milestone(obj) : | Removes the association with the passed milestone.
remove_all_milestones : | Removes associations with all associated milestones.
milestones_dataset : | Returns a dataset that would return the associated milestones, allowing for further filtering/limiting/etc.

If you want to override the behavior of the add_/remove_/remove_all_/ methods or the association setter method, there are private instance methods created that are prepended with an underscore (e.g. _add_milestone or _portfolio=). The private instance methods can be easily overridden, but you shouldn‘t override the public instance methods without calling super, as they deal with callbacks and caching.

By default the classes for the associations are inferred from the association name, so for example the Project#portfolio will return an instance of Portfolio, and Project#milestones will return an array of Milestone instances. You can use the :class option to change which class is used.

Association definitions are also reflected by the class, e.g.:

      Project.associations
      => [:portfolio, :milestones]
      Project.association_reflection(:portfolio)
      => {:type => :many_to_one, :name => :portfolio, ...}

Associations should not have the same names as any of the columns in the model‘s current table they reference. If you are dealing with an existing schema that has a column named status, you can‘t name the association status, you‘d have to name it foo_status or something else. If you give an association the same name as a column, you will probably end up with an association that doesn‘t work, or a SystemStackError.

For a more in depth general overview, as well as a reference guide, see the Association Basics guide. For examples of advanced usage, see the Advanced Associations guide.

### Methods

all_association_reflections apply_association_dataset_opts associate association_reflection associations eager_loading_dataset inherited many_to_many many_to_one one_to_many one_to_one

### Attributes

association_reflections | [R] | All association reflections defined for this model (default: {}).
default_eager_limit_strategy | [RW] | The default :eager_limit_strategy option to use for *_many associations (default: nil)

### Public Instance methods

all_association_reflections()

Array of all association reflections for this model class

[Source]

         # File lib/sequel/model/associations.rb, line 685
    685:         def all_association_reflections
    686:           association_reflections.values
    687:         end

apply_association_dataset_opts(opts, ds)

Given an association reflection and a dataset, apply the :select, :conditions, :order, :eager, :distinct, and :eager_block association options to the given dataset and return the dataset or a modified copy of it.

[Source]

         # File lib/sequel/model/associations.rb, line 693
    693:         def apply_association_dataset_opts(opts, ds)
    694:           ds = ds.select(*opts.select) if opts.select
    695:           if c = opts[:conditions]
    696:             ds = (c.is_a?(Array) && !Sequel.condition_specifier?(c)) ? ds.filter(*c) : ds.filter(c)
    697:           end
    698:           ds = ds.order(*opts[:order]) if opts[:order]
    699:           ds = ds.eager(opts[:eager]) if opts[:eager]
    700:           ds = ds.distinct if opts[:distinct]
    701:           ds = opts[:eager_block].call(ds) if opts[:eager_block]
    702:           ds
    703:         end

associate(type, name, opts = {}, &block)

Associates a related model with the current model. The following types are supported:

:many_to_one : | Foreign key in current model‘s table points to associated model‘s primary key. Each associated model object can be associated with more than one current model objects. Each current model object can be associated with only one associated model object.
:one_to_many : | Foreign key in associated model‘s table points to this model‘s primary key. Each current model object can be associated with more than one associated model objects. Each associated model object can be associated with only one current model object.
:one_to_one : | Similar to one_to_many in terms of foreign keys, but only one object is associated to the current object through the association. The methods created are similar to many_to_one, except that the one_to_one setter method saves the passed object.
:many_to_many : | A join table is used that has a foreign key that points to this model‘s primary key and a foreign key that points to the associated model‘s primary key. Each current model object can be associated with many associated model objects, and each associated model object can be associated with many current model objects.

The following options can be supplied:

### All Types

:after_add : | Symbol, Proc, or array of both/either specifying a callback to call after a new item is added to the association.
:after_load : | Symbol, Proc, or array of both/either specifying a callback to call after the associated record(s) have been retrieved from the database.
:after_remove : | Symbol, Proc, or array of both/either specifying a callback to call after an item is removed from the association.
:after_set : | Symbol, Proc, or array of both/either specifying a callback to call after an item is set using the association setter method.
:allow_eager : | If set to false, you cannot load the association eagerly via eager or eager_graph
:before_add : | Symbol, Proc, or array of both/either specifying a callback to call before a new item is added to the association.
:before_remove : | Symbol, Proc, or array of both/either specifying a callback to call before an item is removed from the association.
:before_set : | Symbol, Proc, or array of both/either specifying a callback to call before an item is set using the association setter method.
:cartesian_product_number : | the number of joins completed by this association that could cause more than one row for each row in the current table (default: 0 for many_to_one and one_to_one associations, 1 for one_to_many and many_to_many associations).
:class : | The associated class or its name. If not given, uses the association‘s name, which is camelized (and singularized unless the type is :many_to_one or :one_to_one)
:clone : | Merge the current options and block into the options and block used in defining the given association. Can be used to DRY up a bunch of similar associations that all share the same options such as :class and :key, while changing the order and block used.
:conditions : | The conditions to use to filter the association, can be any argument passed to filter.
:dataset : | A proc that is instance_evaled to get the base dataset to use for the _dataset method (before the other options are applied).
:distinct : | Use the DISTINCT clause when selecting associating object, both when lazy loading and eager loading via .eager (but not when using .eager_graph).
:eager : | The associations to eagerly load via `eager` when loading the associated object(s).
:eager_block : | If given, use the block instead of the default block when eagerly loading. To not use a block when eager loading (when one is used normally), set to nil.
:eager_graph : | The associations to eagerly load via `eager_graph` when loading the associated object(s). many_to_many associations with this option cannot be eagerly loaded via `eager`.
:eager_grapher : | A proc to use to implement eager loading via `eager_graph`, overriding the default. Takes one or three arguments. If three arguments, they are a dataset, an alias to use for the table to graph for this association, and the alias that was used for the current table (since you can cascade associations). If one argument, is passed a hash with keys :self, :table_alias, and :implicit_qualifier, corresponding to the three arguments, and an optional additional key :eager_block, a callback accepting one argument, the associated dataset. This is used to customize the association at query time. Should return a copy of the dataset with the association graphed into it.
:eager_limit_strategy : | Determines the strategy used for enforcing limits when eager loading associations via the `eager` method. For one_to_one associations, no strategy is used by default, and for *_many associations, the :ruby strategy is used by default, which still retrieves all records but slices the resulting array after the association is retrieved. You can pass a `true` value for this option to have Sequel pick what it thinks is the best choice for the database, or specify a specific symbol to manually select a strategy. one_to_one associations support :distinct_on, :window_function, and :correlated_subquery. *_many associations support :ruby, :window_function, and :correlated_subquery.
:eager_loader : | A proc to use to implement eager loading, overriding the default. Takes a single hash argument, with at least the keys: :rows, which is an array of current model instances, :associations, which is a hash of dependent associations, :self, which is the dataset doing the eager loading, :eager_block, which is a dynamic callback that should be called with the dataset, and :id_map, which is a mapping of key values to arrays of current model instances. In the proc, the associated records should be queried from the database and the associations cache for each record should be populated.
:eager_loader_key : | A symbol for the key column to use to populate the key_hash for the eager loader. Can be set to nil to not populate the key_hash.
:extend : | A module or array of modules to extend the dataset with.
:graph_alias_base : | The base name to use for the table alias when eager graphing. Defaults to the name of the association. If the alias name has already been used in the query, Sequel will create a unique alias by appending a numeric suffix (e.g. alias_0, alias_1, …) until the alias is unique.
:graph_block : | The block to pass to join_table when eagerly loading the association via `eager_graph`.
:graph_conditions : | The additional conditions to use on the SQL join when eagerly loading the association via `eager_graph`. Should be a hash or an array of two element arrays. If not specified, the :conditions option is used if it is a hash or array of two element arrays.
:graph_join_type : | The type of SQL join to use when eagerly loading the association via eager_graph. Defaults to :left_outer.
:graph_only_conditions : | The conditions to use on the SQL join when eagerly loading the association via `eager_graph`, instead of the default conditions specified by the foreign/primary keys. This option causes the :graph_conditions option to be ignored.
:graph_select : | A column or array of columns to select from the associated table when eagerly loading the association via `eager_graph`. Defaults to all columns in the associated table.
:limit : | Limit the number of records to the provided value. Use an array with two elements for the value to specify a limit (first element) and an offset (second element).
:methods_module : | The module that methods the association creates will be placed into. Defaults to the module containing the model‘s columns.
:order : | the column(s) by which to order the association dataset. Can be a singular column symbol or an array of column symbols.
:order_eager_graph : | Whether to add the association‘s order to the graphed dataset‘s order when graphing via `eager_graph`. Defaults to true, so set to false to disable.
:read_only : | Do not add a setter method (for many_to_one or one_to_one associations), or add_/remove_/remove_all_ methods (for one_to_many and many_to_many associations).
:reciprocal : | the symbol name of the reciprocal association, if it exists. By default, Sequel will try to determine it by looking at the associated model‘s assocations for a association that matches the current association‘s key(s). Set to nil to not use a reciprocal.
:select : | the columns to select. Defaults to the associated class‘s table_name.* in a many_to_many association, which means it doesn‘t include the attributes from the join table. If you want to include the join table attributes, you can use this option, but beware that the join table attributes can clash with attributes from the model table, so you should alias any attributes that have the same name in both the join table and the associated table.
:validate : | Set to false to not validate when implicitly saving any associated object.

### :many_to_one

:key : | foreign key in current model‘s table that references associated model‘s primary key, as a symbol. Defaults to :"#{name}_id". Can use an array of symbols for a composite key association.
:key_column : | Similar to, and usually identical to, :key, but :key refers to the model method to call, where :key_column refers to the underlying column. Should only be used if the the model method differs from the foreign key column, in conjunction with defining a model alias method for the key column.
:primary_key : | column in the associated table that :key option references, as a symbol. Defaults to the primary key of the associated table. Can use an array of symbols for a composite key association.
:primary_key_method : | the method symbol or array of method symbols to call on the associated object to get the foreign key values. Defaults to :primary_key option.
:qualify : | Whether to use qualifier primary keys when loading the association. The default is true, so you must set to false to not qualify. Qualification rarely causes problems, but it‘s necessary to disable in some cases, such as when you are doing a JOIN USING operation on the column on Oracle.

### :one_to_many and :one_to_one

:key : | foreign key in associated model‘s table that references current model‘s primary key, as a symbol. Defaults to :"#{self.name.underscore}_id". Can use an array of symbols for a composite key association.
:key_method : | the method symbol or array of method symbols to call on the associated object to get the foreign key values. Defaults to :key option.
:primary_key : | column in the current table that :key option references, as a symbol. Defaults to primary key of the current table. Can use an array of symbols for a composite key association.
:primary_key_column : | Similar to, and usually identical to, :primary_key, but :primary_key refers to the model method call, where :primary_key_column refers to the underlying column. Should only be used if the the model method differs from the primary key column, in conjunction with defining a model alias method for the primary key column.

### :many_to_many

:graph_join_table_block : | The block to pass to `join_table` for the join table when eagerly loading the association via `eager_graph`.
:graph_join_table_conditions : | The additional conditions to use on the SQL join for the join table when eagerly loading the association via `eager_graph`. Should be a hash or an array of two element arrays.
:graph_join_table_join_type : | The type of SQL join to use for the join table when eagerly loading the association via `eager_graph`. Defaults to the :graph_join_type option or :left_outer.
:graph_join_table_only_conditions : | The conditions to use on the SQL join for the join table when eagerly loading the association via `eager_graph`, instead of the default conditions specified by the foreign/primary keys. This option causes the :graph_join_table_conditions option to be ignored.
:join_table : | name of table that includes the foreign keys to both the current model and the associated model, as a symbol. Defaults to the name of current model and name of associated model, pluralized, underscored, sorted, and joined with ‘_’.
:join_table_block : | proc that can be used to modify the dataset used in the add/remove/remove_all methods. Should accept a dataset argument and return a modified dataset if present.
:left_key : | foreign key in join table that points to current model‘s primary key, as a symbol. Defaults to :"#{self.name.underscore}_id". Can use an array of symbols for a composite key association.
:left_primary_key : | column in current table that :left_key points to, as a symbol. Defaults to primary key of current table. Can use an array of symbols for a composite key association.
:left_primary_key_column : | Similar to, and usually identical to, :left_primary_key, but :left_primary_key refers to the model method to call, where :left_primary_key_column refers to the underlying column. Should only be used if the model method differs from the left primary key column, in conjunction with defining a model alias method for the left primary key column.
:right_key : | foreign key in join table that points to associated model‘s primary key, as a symbol. Defaults to :"#{name.to_s.singularize}_id". Can use an array of symbols for a composite key association.
:right_primary_key : | column in associated table that :right_key points to, as a symbol. Defaults to primary key of the associated table. Can use an array of symbols for a composite key association.
:right_primary_key_method : | the method symbol or array of method symbols to call on the associated object to get the foreign key values for the join table. Defaults to :right_primary_key option.
:uniq : | Adds a after_load callback that makes the array of objects unique.

[Source]

         # File lib/sequel/model/associations.rb, line 901
    901:         def associate(type, name, opts = {}, &block)
    902:           raise(Error, 'one_to_many association type with :one_to_one option removed, used one_to_one association type') if opts[:one_to_one] && type == :one_to_many
    903:           raise(Error, 'invalid association type') unless assoc_class = ASSOCIATION_TYPES[type]
    904:           raise(Error, 'Model.associate name argument must be a symbol') unless Symbol === name
    905:           raise(Error, ':eager_loader option must have an arity of 1 or 3') if opts[:eager_loader] && ![1, 3].include?(opts[:eager_loader].arity)
    906:           raise(Error, ':eager_grapher option must have an arity of 1 or 3') if opts[:eager_grapher] && ![1, 3].include?(opts[:eager_grapher].arity)
    907:
    908:           # dup early so we don't modify opts
    909:           orig_opts = opts.dup
    910:           if opts[:clone]
    911:             cloned_assoc = association_reflection(opts[:clone])
    912:             raise(Error, "cannot clone an association to an association of different type (association #{name} with type #{type} cloning #{opts[:clone]} with type #{cloned_assoc[:type]})") unless cloned_assoc[:type] == type || [cloned_assoc[:type], type].all?{|t| [:one_to_many, :one_to_one].include?(t)}
    913:             orig_opts = cloned_assoc[:orig_opts].merge(orig_opts)
    914:           end
    915:           opts = orig_opts.merge(:type => type, :name => name, :cache=>{}, :model => self)
    916:           opts[:block] = block if block
    917:           opts = assoc_class.new.merge!(opts)
    918:           opts[:eager_block] = block unless opts.include?(:eager_block)
    919:           if !opts.has_key?(:predicate_key) && opts.has_key?(:eager_loading_predicate_key)
    920:             opts[:predicate_key] = opts[:eager_loading_predicate_key]
    921:           end
    922:           opts[:graph_join_type] ||= :left_outer
    923:           opts[:order_eager_graph] = true unless opts.include?(:order_eager_graph)
    924:           conds = opts[:conditions]
    925:           opts[:graph_alias_base] ||= name
    926:           opts[:graph_conditions] = conds if !opts.include?(:graph_conditions) and Sequel.condition_specifier?(conds)
    927:           opts[:graph_conditions] = opts.fetch(:graph_conditions, []).to_a
    928:           opts[:graph_select] = Array(opts[:graph_select]) if opts[:graph_select]
    929:           [:before_add, :before_remove, :after_add, :after_remove, :after_load, :before_set, :after_set, :extend].each do |cb_type|
    930:             opts[cb_type] = Array(opts[cb_type])
    931:           end
    932:           late_binding_class_option(opts, opts.returns_array? ? singularize(name) : name)
    933:
    934:           # Remove :class entry if it exists and is nil, to work with cached_fetch
    935:           opts.delete(:class) unless opts[:class]
    936:
    937:           send("def_#{type}""def_#{type}", opts)
    938:
    939:           orig_opts.delete(:clone)
    940:           orig_opts.merge!(:class_name=>opts[:class_name], :class=>opts[:class], :block=>block)
    941:           opts[:orig_opts] = orig_opts
    942:           # don't add to association_reflections until we are sure there are no errors
    943:           association_reflections[name] = opts
    944:         end

association_reflection(name)

The association reflection hash for the association of the given name.

[Source]

         # File lib/sequel/model/associations.rb, line 947
    947:         def association_reflection(name)
    948:           association_reflections[name]
    949:         end

associations()

Array of association name symbols

[Source]

         # File lib/sequel/model/associations.rb, line 952
    952:         def associations
    953:           association_reflections.keys
    954:         end

eager_loading_dataset(opts, ds, select, associations, eager_options={})

Modify and return eager loading dataset based on association options.

[Source]

         # File lib/sequel/model/associations.rb, line 957
    957:         def eager_loading_dataset(opts, ds, select, associations, eager_options={})
    958:           ds = apply_association_dataset_opts(opts, ds)
    959:           ds = ds.select(*select) if select
    960:           if opts[:eager_graph]
    961:             raise(Error, "cannot eagerly load a #{opts[:type]} association that uses :eager_graph") if opts.eager_loading_use_associated_key?
    962:             ds = ds.eager_graph(opts[:eager_graph])
    963:           end
    964:           ds = ds.eager(associations) unless Array(associations).empty?
    965:           ds = eager_options[:eager_block].call(ds) if eager_options[:eager_block]
    966:           if opts.eager_loading_use_associated_key?
    967:             ds = if opts[:uses_left_composite_keys]
    968:               ds.select_append(*opts.associated_key_alias.zip(opts.predicate_keys).map{|a, k| SQL::AliasedExpression.new(k, a)})
    969:             else
    970:               ds.select_append(SQL::AliasedExpression.new(opts.predicate_key, opts.associated_key_alias))
    971:             end
    972:           end
    973:           ds
    974:         end

inherited(subclass)

Copy the association reflections to the subclass

[Source]

         # File lib/sequel/model/associations.rb, line 977
    977:         def inherited(subclass)
    978:           super
    979:           subclass.instance_variable_set(:@association_reflections, association_reflections.dup)
    980:           subclass.default_eager_limit_strategy =  default_eager_limit_strategy
    981:         end

many_to_many(name, opts={}, &block)

Shortcut for adding a many_to_many association, see associate

[Source]

         # File lib/sequel/model/associations.rb, line 984
    984:         def many_to_many(name, opts={}, &block)
    985:           associate(:many_to_many, name, opts, &block)
    986:         end

many_to_one(name, opts={}, &block)

Shortcut for adding a many_to_one association, see associate

[Source]

         # File lib/sequel/model/associations.rb, line 989
    989:         def many_to_one(name, opts={}, &block)
    990:           associate(:many_to_one, name, opts, &block)
    991:         end

one_to_many(name, opts={}, &block)

Shortcut for adding a one_to_many association, see associate

[Source]

         # File lib/sequel/model/associations.rb, line 994
    994:         def one_to_many(name, opts={}, &block)
    995:           associate(:one_to_many, name, opts, &block)
    996:         end

one_to_one(name, opts={}, &block)

Shortcut for adding a one_to_one association, see associate.

[Source]

          # File lib/sequel/model/associations.rb, line 999
     999:         def one_to_one(name, opts={}, &block)
    1000:           associate(:one_to_one, name, opts, &block)
    1001:         end

[Validate]