Module Sequel::Model::Associations::ClassMethods
In: lib/sequel/model/associations.rb
lib/sequel/model/deprecated.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
    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.
  • 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, there are private instance methods created that a prepended with an underscore (e.g. _add_milestone). 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.

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

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

Methods

Attributes

association_reflections  [R]  All association reflections defined for this model (default: none).

Public Instance methods

Array of all association reflections for this model class

[Source]

     # File lib/sequel/model/associations.rb, line 335
335:         def all_association_reflections
336:           association_reflections.values
337:         end

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.
  • :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.

A one to one relationship can be set up with a many_to_one association on the table with the foreign key, and a one_to_many association with the :one_to_one option specified on the table without the foreign key. The two associations will operate similarly, except that the many_to_one association setter doesn‘t update the database until you call save manually. Also, in most cases you need to specify the plural association name when using one_to_many with the :one_to_one option.

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. Not called when eager loading via eager_graph, but called when eager loading via eager.
    • :after_remove - Symbol, Proc, or array of both/either specifying a callback to call after an item is removed from the association.
    • :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.
    • :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)
    • :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).
    • :eager - The associations to eagerly load via eager when loading the associated object(s). For many_to_one associations, this is ignored unless this association is being eagerly loaded, as it doesn‘t save queries unless multiple objects can be loaded at once.
    • :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). For many_to_one associations, this is ignored unless this association is being eagerly loaded, as it doesn‘t save queries unless multiple objects can be loaded at once.
    • :eager_grapher - A proc to use to implement eager loading via eager graph, overriding the default. Takes three arguments, 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), Should return a copy of the dataset with the association graphed into it.
    • :eager_loader - A proc to use to implement eager loading, overriding the default. Takes three arguments, a key hash (used solely to enhance performance), an array of records, and a hash of dependent associations. The associated records should be queried from the database and the associations cache for each record should be populated for this to work correctly.
    • :extend - A module or array of modules to extend the dataset with.
    • :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 all two pairs. If not specified, the :conditions option is used if it is a hash or array of all two pairs.
    • :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 arguments for the value to specify a limit and an offset.
    • :order - the column(s) by which to order the association dataset. Can be a singular column or an array.
    • :order_eager_graph - Whether to add the order to the 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_many with :one_to_one), or add_/remove_/remove_all_ methods (for one_to_many, many_to_many)
    • :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 attributes 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.
  • :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".
    • :primary_key - column in the associated table that :key option references, as a symbol. Defaults to the primary key of the associated table.
  • :one_to_many:
    • :key - foreign key in associated model‘s table that references current model‘s primary key, as a symbol. Defaults to :"#{self.name.underscore}_id".
    • :one_to_one: Create a getter and setter similar to those of many_to_one associations. The getter returns a singular matching record, or raises an error if multiple records match. The setter updates the record given and removes associations with all other records. When this option is used, the other association methods usually added are either removed or made private, so using this is similar to using many_to_one, in terms of the methods it adds, the main difference is that the foreign key is in the associated table instead of the current table. Note that using this option still requires you to use a plural name when creating and using the association (e.g. for reflections, eager loading, etc.).
    • :primary_key - column in the current table that :key option references, as a symbol. Defaults to primary key of the current table.
  • :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 all two pairs.
    • :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 ‘_’.
    • :left_key - foreign key in join table that points to current model‘s primary key, as a symbol. Defaults to :"#{self.name.underscore}_id".
    • :left_primary_key - column in current table that :left_key points to, as a symbol. Defaults to primary key of current table.
    • :right_key - foreign key in join table that points to associated model‘s primary key, as a symbol. Defaults to Defaults to :"#{name.to_s.singularize}_id".
    • :right_primary_key - column in associated table that :right_key points to, as a symbol. Defaults to primary key of the associated table.
    • :uniq - Adds a after_load callback that makes the array of objects unique.

[Source]

     # File lib/sequel/model/associations.rb, line 486
486:         def associate(type, name, opts = {}, &block)
487:           raise(Error, 'invalid association type') unless assoc_class = ASSOCIATION_TYPES[type]
488:           raise(Error, 'Model.associate name argument must be a symbol') unless Symbol === name
489:       
490:           # merge early so we don't modify opts
491:           orig_opts = opts.dup
492:           orig_opts = association_reflection(opts[:clone])[:orig_opts].merge(orig_opts) if opts[:clone]
493:           opts = orig_opts.merge(:type => type, :name => name, :cache => true, :model => self)
494:           opts[:block] = block if block
495:           opts = assoc_class.new.merge!(opts)
496:           opts[:eager_block] = block unless opts.include?(:eager_block)
497:           opts[:graph_join_type] ||= :left_outer
498:           opts[:order_eager_graph] = true unless opts.include?(:order_eager_graph)
499:           conds = opts[:conditions]
500:           opts[:graph_conditions] = conds if !opts.include?(:graph_conditions) and Sequel.condition_specifier?(conds)
501:           opts[:graph_conditions] = opts[:graph_conditions] ? opts[:graph_conditions].to_a : []
502:           opts[:graph_select] = Array(opts[:graph_select]) if opts[:graph_select]
503:           [:before_add, :before_remove, :after_add, :after_remove, :after_load, :extend].each do |cb_type|
504:             opts[cb_type] = Array(opts[cb_type])
505:           end
506:       
507:           # find class
508:           case opts[:class]
509:             when String, Symbol
510:               # Delete :class to allow late binding
511:               opts[:class_name] ||= opts.delete(:class).to_s
512:             when Class
513:               opts[:class_name] ||= opts[:class].name
514:           end
515:       
516:           send("def_#{type}""def_#{type}", opts)
517:       
518:           orig_opts.delete(:clone)
519:           orig_opts.merge!(:class_name=>opts[:class_name], :class=>opts[:class], :block=>block)
520:           opts[:orig_opts] = orig_opts
521:           # don't add to association_reflections until we are sure there are no errors
522:           association_reflections[name] = opts
523:         end

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

[Source]

     # File lib/sequel/model/associations.rb, line 526
526:         def association_reflection(name)
527:           association_reflections[name]
528:         end

Array of association name symbols

[Source]

     # File lib/sequel/model/associations.rb, line 531
531:         def associations
532:           association_reflections.keys
533:         end

[Source]

     # File lib/sequel/model/deprecated.rb, line 187
187:         def belongs_to(*args, &block)
188:           Deprecation.deprecate('Sequel::Model.belongs_to', 'Use Sequel::Model.many_to_one')
189:           many_to_one(*args, &block)
190:         end

Modify and return eager loading dataset based on association options

[Source]

     # File lib/sequel/model/associations.rb, line 536
536:         def eager_loading_dataset(opts, ds, select, associations)
537:           ds = ds.select(*select) if select
538:           ds = ds.filter(opts[:conditions]) if opts[:conditions]
539:           ds = ds.order(*opts[:order]) if opts[:order]
540:           ds = ds.eager(opts[:eager]) if opts[:eager]
541:           ds = ds.eager_graph(opts[:eager_graph]) if opts[:eager_graph]
542:           ds = ds.eager(associations) unless Array(associations).empty?
543:           ds = opts[:eager_block].call(ds) if opts[:eager_block]
544:           ds
545:         end

[Source]

     # File lib/sequel/model/deprecated.rb, line 197
197:         def has_and_belongs_to_many(*args, &block)
198:           Deprecation.deprecate('Sequel::Model.has_and_belongs_to_many', 'Use Sequel::Model.many_to_many')
199:           many_to_many(*args, &block)
200:         end

[Source]

     # File lib/sequel/model/deprecated.rb, line 192
192:         def has_many(*args, &block)
193:           Deprecation.deprecate('Sequel::Model.has_many', 'Use Sequel::Model.one_to_many')
194:           one_to_many(*args, &block)
195:         end

Copy the association reflections to the subclass

[Source]

     # File lib/sequel/model/associations.rb, line 548
548:         def inherited(subclass)
549:           super
550:           subclass.instance_variable_set(:@association_reflections, @association_reflections.dup)
551:         end

Shortcut for adding a many_to_many association, see associate

[Source]

     # File lib/sequel/model/associations.rb, line 554
554:         def many_to_many(*args, &block)
555:           associate(:many_to_many, *args, &block)
556:         end

Shortcut for adding a many_to_one association, see associate

[Source]

     # File lib/sequel/model/associations.rb, line 559
559:         def many_to_one(*args, &block)
560:           associate(:many_to_one, *args, &block)
561:         end

Shortcut for adding a one_to_many association, see associate

[Source]

     # File lib/sequel/model/associations.rb, line 564
564:         def one_to_many(*args, &block)
565:           associate(:one_to_many, *args, &block)
566:         end

[Validate]