Method: Sequel::Model::Associations::ClassMethods#associate

Defined in:
lib/sequel/model/associations.rb

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

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

    • :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 associations, 1 for *_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)

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

    • :eager_loader_key - A symbol for the key column to use to populate the key hash for the eager loader.

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

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

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

  • :one_to_many:

    • :key - foreign key in associated model’s table that references current model’s primary key, as a symbol. Defaults to :“#Sequel::Model::Associations::ClassMethods.selfself.nameself.name.underscore_id”. Can use an array of symbols for a composite key association.

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

  • :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 :“#Sequel::Model::Associations::ClassMethods.selfself.nameself.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.

    • :right_key - foreign key in join table that points to associated model’s primary key, as a symbol. Defaults to Defaults to :“#Sequel::Model::Associations::ClassMethods.namename.to_sname.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.

    • :uniq - Adds a after_load callback that makes the array of objects unique.

Raises:



607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
# File 'lib/sequel/model/associations.rb', line 607

def associate(type, name, opts = {}, &block)
  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
  raise(Error, 'invalid association type') unless assoc_class = ASSOCIATION_TYPES[type]
  raise(Error, 'Model.associate name argument must be a symbol') unless Symbol === name
      
  # merge early so we don't modify opts
  orig_opts = opts.dup
  orig_opts = association_reflection(opts[:clone])[:orig_opts].merge(orig_opts) if opts[:clone]
  opts = orig_opts.merge(:type => type, :name => name, :cache => true, :model => self)
  opts[:block] = block if block
  opts = assoc_class.new.merge!(opts)
  opts[:eager_block] = block unless opts.include?(:eager_block)
  opts[:graph_join_type] ||= :left_outer
  opts[:order_eager_graph] = true unless opts.include?(:order_eager_graph)
  conds = opts[:conditions]
  opts[:graph_conditions] = conds if !opts.include?(:graph_conditions) and Sequel.condition_specifier?(conds)
  opts[:graph_conditions] = opts.fetch(:graph_conditions, []).to_a
  opts[:graph_select] = Array(opts[:graph_select]) if opts[:graph_select]
  [:before_add, :before_remove, :after_add, :after_remove, :after_load, :before_set, :after_set, :extend].each do |cb_type|
    opts[cb_type] = Array(opts[cb_type])
  end
  late_binding_class_option(opts, opts.returns_array? ? singularize(name) : name)
  
  send(:"def_#{type}", opts)
      
  orig_opts.delete(:clone)
  orig_opts.merge!(:class_name=>opts[:class_name], :class=>opts[:class], :block=>block)
  opts[:orig_opts] = orig_opts
  # don't add to association_reflections until we are sure there are no errors
  association_reflections[name] = opts
end