Class Index [+]

Quicksearch

Sequel::Model::Associations::ClassMethods

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.

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() click to toggle source

Array of all association reflections for this model class

     # File lib/sequel/model/associations.rb, line 672
672:         def all_association_reflections
673:           association_reflections.values
674:         end
apply_association_dataset_opts(opts, ds) click to toggle source

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.

     # File lib/sequel/model/associations.rb, line 680
680:         def apply_association_dataset_opts(opts, ds)
681:           ds = ds.select(*opts.select) if opts.select
682:           if c = opts[:conditions]
683:             ds = (c.is_a?(Array) && !Sequel.condition_specifier?(c)) ? ds.filter(*c) : ds.filter(c)
684:           end
685:           ds = ds.order(*opts[:order]) if opts[:order]
686:           ds = ds.eager(opts[:eager]) if opts[:eager]
687:           ds = ds.distinct if opts[:distinct]
688:           ds = opts[:eager_block].call(ds) if opts[:eager_block]
689:           ds
690:         end
associate(type, name, opts = {}, &block) click to toggle source

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 one or three arguments. If three arguments, the first should be a key hash (used solely to enhance performance), the second an array of records, and the third a hash of dependent associations. If one argument, is passed a hash with keys :key_hash, :rows, and :associations, corresponding to the three arguments, and an additional key :self, which is the dataset doing the eager loading. 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.

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

     # File lib/sequel/model/associations.rb, line 888
888:         def associate(type, name, opts = {}, &block)
889:           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
890:           raise(Error, 'invalid association type') unless assoc_class = ASSOCIATION_TYPES[type]
891:           raise(Error, 'Model.associate name argument must be a symbol') unless Symbol === name
892:           raise(Error, ':eager_loader option must have an arity of 1 or 3') if opts[:eager_loader] && ![1, 3].include?(opts[:eager_loader].arity)
893:           raise(Error, ':eager_grapher option must have an arity of 1 or 3') if opts[:eager_grapher] && ![1, 3].include?(opts[:eager_grapher].arity)
894: 
895:           # dup early so we don't modify opts
896:           orig_opts = opts.dup
897:           orig_opts = association_reflection(opts[:clone])[:orig_opts].merge(orig_opts) if opts[:clone]
898:           opts = orig_opts.merge(:type => type, :name => name, :cache=>{}, :model => self)
899:           opts[:block] = block if block
900:           opts = assoc_class.new.merge!(opts)
901:           opts[:eager_block] = block unless opts.include?(:eager_block)
902:           opts[:graph_join_type] ||= :left_outer
903:           opts[:order_eager_graph] = true unless opts.include?(:order_eager_graph)
904:           conds = opts[:conditions]
905:           opts[:graph_alias_base] ||= name
906:           opts[:graph_conditions] = conds if !opts.include?(:graph_conditions) and Sequel.condition_specifier?(conds)
907:           opts[:graph_conditions] = opts.fetch(:graph_conditions, []).to_a
908:           opts[:graph_select] = Array(opts[:graph_select]) if opts[:graph_select]
909:           [:before_add, :before_remove, :after_add, :after_remove, :after_load, :before_set, :after_set, :extend].each do |cb_type|
910:             opts[cb_type] = Array(opts[cb_type])
911:           end
912:           late_binding_class_option(opts, opts.returns_array? ? singularize(name) : name)
913:           
914:           # Remove :class entry if it exists and is nil, to work with cached_fetch
915:           opts.delete(:class) unless opts[:class]
916:           
917:           send(:"def_#{type}", opts)
918:       
919:           orig_opts.delete(:clone)
920:           orig_opts.merge!(:class_name=>opts[:class_name], :class=>opts[:class], :block=>block)
921:           opts[:orig_opts] = orig_opts
922:           # don't add to association_reflections until we are sure there are no errors
923:           association_reflections[name] = opts
924:         end
association_reflection(name) click to toggle source

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

     # File lib/sequel/model/associations.rb, line 927
927:         def association_reflection(name)
928:           association_reflections[name]
929:         end
associations() click to toggle source

Array of association name symbols

     # File lib/sequel/model/associations.rb, line 932
932:         def associations
933:           association_reflections.keys
934:         end
eager_loading_dataset(opts, ds, select, associations, eager_options={}) click to toggle source

Modify and return eager loading dataset based on association options.

     # File lib/sequel/model/associations.rb, line 937
937:         def eager_loading_dataset(opts, ds, select, associations, eager_options={})
938:           ds = apply_association_dataset_opts(opts, ds)
939:           ds = ds.select(*select) if select
940:           if opts[:eager_graph]
941:             raise(Error, "cannot eagerly load a #{opts[:type]} association that uses :eager_graph") if opts.eager_loading_use_associated_key?
942:             ds = ds.eager_graph(opts[:eager_graph])
943:           end
944:           ds = ds.eager(associations) unless Array(associations).empty?
945:           ds = eager_options[:eager_block].call(ds) if eager_options[:eager_block]
946:           if opts.eager_loading_use_associated_key?
947:             ds = if opts[:uses_left_composite_keys]
948:               ds.select_append(*opts.associated_key_alias.zip(opts.eager_loading_predicate_key).map{|a, k| SQL::AliasedExpression.new(k, a)})
949:             else
950:               ds.select_append(SQL::AliasedExpression.new(opts.eager_loading_predicate_key, opts.associated_key_alias))
951:             end
952:           end
953:           ds
954:         end
inherited(subclass) click to toggle source

Copy the association reflections to the subclass

     # File lib/sequel/model/associations.rb, line 957
957:         def inherited(subclass)
958:           super
959:           subclass.instance_variable_set(:@association_reflections, association_reflections.dup)
960:           subclass.default_eager_limit_strategy =  default_eager_limit_strategy
961:         end
many_to_many(name, opts={}, &block) click to toggle source

Shortcut for adding a many_to_many association, see #

     # File lib/sequel/model/associations.rb, line 964
964:         def many_to_many(name, opts={}, &block)
965:           associate(:many_to_many, name, opts, &block)
966:         end
many_to_one(name, opts={}, &block) click to toggle source

Shortcut for adding a many_to_one association, see #

     # File lib/sequel/model/associations.rb, line 969
969:         def many_to_one(name, opts={}, &block)
970:           associate(:many_to_one, name, opts, &block)
971:         end
one_to_many(name, opts={}, &block) click to toggle source

Shortcut for adding a one_to_many association, see #

     # File lib/sequel/model/associations.rb, line 974
974:         def one_to_many(name, opts={}, &block)
975:           associate(:one_to_many, name, opts, &block)
976:         end
one_to_one(name, opts={}, &block) click to toggle source

Shortcut for adding a one_to_one association, see #.

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

Private Instance Methods

apply_correlated_subquery_eager_limit_strategy(ds, opts) click to toggle source

Use a correlated subquery to limit the results of the eager loading dataset.

      # File lib/sequel/model/associations.rb, line 986
 986:         def apply_correlated_subquery_eager_limit_strategy(ds, opts)
 987:           klass = opts.associated_class
 988:           kds = klass.dataset
 989:           dsa = ds.send(:dataset_alias, 1)
 990:           raise Error, "can't use a correlated subquery if the associated class (#{opts.associated_class.inspect}) does not have a primary key" unless pk = klass.primary_key
 991:           pka = Array(pk)
 992:           raise Error, "can't use a correlated subquery if the associated class (#{opts.associated_class.inspect}) has a composite primary key and the database does not support multiple column IN" if pka.length > 1 && !ds.supports_multiple_column_in?
 993:           table = kds.opts[:from]
 994:           raise Error, "can't use a correlated subquery unless the associated class (#{opts.associated_class.inspect}) uses a single FROM table" unless table && table.length == 1
 995:           table = table.first
 996:           if order = ds.opts[:order]
 997:             oproc = lambda do |x|
 998:               case x
 999:               when Symbol
1000:                 t, c, a = ds.send(:split_symbol, x)
1001:                 if t && t.to_sym == table
1002:                   SQL::QualifiedIdentifier.new(dsa, c)
1003:                 else
1004:                   x
1005:                 end
1006:               when SQL::QualifiedIdentifier
1007:                 if x.table == table
1008:                   SQL::QualifiedIdentifier.new(dsa, x.column)
1009:                 else
1010:                   x
1011:                 end
1012:               when SQL::OrderedExpression
1013:                 SQL::OrderedExpression.new(oproc.call(x.expression), x.descending, :nulls=>x.nulls)
1014:               else
1015:                 x
1016:               end
1017:             end
1018:             order = order.map(&oproc) 
1019:           end
1020:           limit, offset = opts.limit_and_offset
1021: 
1022:           subquery = yield kds.
1023:             unlimited.
1024:             from(SQL::AliasedExpression.new(table, dsa)).
1025:             select(*pka.map{|k| SQL::QualifiedIdentifier.new(dsa, k)}).
1026:             order(*order).
1027:             limit(limit, offset)
1028: 
1029:           pk = if pk.is_a?(Array)
1030:             pk.map{|k| SQL::QualifiedIdentifier.new(table, k)}
1031:           else
1032:             SQL::QualifiedIdentifier.new(table, pk)
1033:           end
1034:           ds.filter(pk=>subquery)
1035:         end
apply_window_function_eager_limit_strategy(ds, opts) click to toggle source

Use a window function to limit the results of the eager loading dataset.

      # File lib/sequel/model/associations.rb, line 1038
1038:         def apply_window_function_eager_limit_strategy(ds, opts)
1039:           rn = ds.row_number_column 
1040:           limit, offset = opts.limit_and_offset
1041:           ds = ds.unordered.select_append{row_number(:over, :partition=>opts.eager_loading_predicate_key, :order=>ds.opts[:order]){}.as(rn)}.from_self
1042:           ds = if opts[:type] == :one_to_one
1043:             ds.where(rn => 1)
1044:           elsif offset
1045:             offset += 1
1046:             ds.where(rn => (offset...(offset+limit))) 
1047:           else
1048:             ds.where{SQL::Identifier.new(rn) <= limit} 
1049:           end
1050:         end
association_module(opts={}) click to toggle source

The module to use for the association’s methods. Defaults to the overridable_methods_module.

      # File lib/sequel/model/associations.rb, line 1054
1054:         def association_module(opts={})
1055:           opts.fetch(:methods_module, overridable_methods_module)
1056:         end
association_module_def(name, opts={}, &block) click to toggle source

Add a method to the module included in the class, so the method can be easily overridden in the class itself while allowing for super to be called.

      # File lib/sequel/model/associations.rb, line 1061
1061:         def association_module_def(name, opts={}, &block)
1062:           association_module(opts).module_eval{define_method(name, &block)}
1063:         end
association_module_private_def(name, opts={}, &block) click to toggle source

Add a private method to the module included in the class.

      # File lib/sequel/model/associations.rb, line 1066
1066:         def association_module_private_def(name, opts={}, &block)
1067:           association_module_def(name, opts, &block)
1068:           association_module(opts).send(:private, name)
1069:         end
def_add_method(opts) click to toggle source

Add the add_ instance method

      # File lib/sequel/model/associations.rb, line 1072
1072:         def def_add_method(opts)
1073:           association_module_def(opts.add_method, opts){|o,*args| add_associated_object(opts, o, *args)}
1074:         end
def_association_dataset_methods(opts) click to toggle source

Adds the association dataset methods to the association methods module.

      # File lib/sequel/model/associations.rb, line 1077
1077:         def def_association_dataset_methods(opts)
1078:           # If a block is given, define a helper method for it, because it takes
1079:           # an argument.  This is unnecessary in Ruby 1.9, as that has instance_exec.
1080:           association_module_private_def(opts.dataset_helper_method, opts, &opts[:block]) if opts[:block]
1081:           association_module_private_def(opts._dataset_method, opts, &opts[:dataset])
1082:           association_module_def(opts.dataset_method, opts){_dataset(opts)}
1083:           def_association_method(opts)
1084:         end
def_association_method(opts) click to toggle source

Adds the association method to the association methods module.

      # File lib/sequel/model/associations.rb, line 1087
1087:         def def_association_method(opts)
1088:           association_module_def(opts.association_method, opts){|*dynamic_opts, &block| load_associated_objects(opts, dynamic_opts[0], &block)}
1089:         end
def_many_to_many(opts) click to toggle source

Configures many_to_many association reflection and adds the related association methods

      # File lib/sequel/model/associations.rb, line 1092
1092:         def def_many_to_many(opts)
1093:           name = opts[:name]
1094:           model = self
1095:           left = (opts[:left_key] ||= opts.default_left_key)
1096:           lcks = opts[:left_keys] = Array(left)
1097:           right = (opts[:right_key] ||= opts.default_right_key)
1098:           rcks = opts[:right_keys] = Array(right)
1099:           left_pk = (opts[:left_primary_key] ||= self.primary_key)
1100:           lcpks = opts[:left_primary_keys] = Array(left_pk)
1101:           lpkc = opts[:left_primary_key_column] ||= left_pk
1102:           lpkcs = opts[:left_primary_key_columns] ||= Array(lpkc)
1103:           elk = opts.eager_loader_key
1104:           raise(Error, "mismatched number of left composite keys: #{lcks.inspect} vs #{lcpks.inspect}") unless lcks.length == lcpks.length
1105:           if opts[:right_primary_key]
1106:             rcpks = Array(opts[:right_primary_key])
1107:             raise(Error, "mismatched number of right composite keys: #{rcks.inspect} vs #{rcpks.inspect}") unless rcks.length == rcpks.length
1108:           end
1109:           uses_lcks = opts[:uses_left_composite_keys] = lcks.length > 1
1110:           uses_rcks = opts[:uses_right_composite_keys] = rcks.length > 1
1111:           opts[:cartesian_product_number] ||= 1
1112:           join_table = (opts[:join_table] ||= opts.default_join_table)
1113:           left_key_alias = opts[:left_key_alias] ||= opts.default_associated_key_alias
1114:           graph_jt_conds = opts[:graph_join_table_conditions] = opts.fetch(:graph_join_table_conditions, []).to_a
1115:           opts[:graph_join_table_join_type] ||= opts[:graph_join_type]
1116:           opts[:after_load].unshift(:array_uniq!) if opts[:uniq]
1117:           opts[:dataset] ||= proc{opts.associated_class.inner_join(join_table, rcks.zip(opts.right_primary_keys) + lcks.zip(lcpks.map{|k| send(k)}))}
1118: 
1119:           opts[:eager_loader] ||= proc do |eo|
1120:             h = eo[:key_hash][elk]
1121:             rows = eo[:rows]
1122:             rows.each{|object| object.associations[name] = []}
1123:             r = rcks.zip(opts.right_primary_keys)
1124:             l = [[opts.qualify(opts.join_table_alias, left), h.keys]]
1125:             ds = model.eager_loading_dataset(opts, opts.associated_class.inner_join(join_table, r + l), nil, eo[:associations], eo)
1126:             case opts.eager_limit_strategy
1127:             when :window_function
1128:               delete_rn = true
1129:               rn = ds.row_number_column
1130:               ds = apply_window_function_eager_limit_strategy(ds, opts)
1131:             when :correlated_subquery
1132:               ds = apply_correlated_subquery_eager_limit_strategy(ds, opts) do |xds|
1133:                 dsa = ds.send(:dataset_alias, 2)
1134:                 xds.inner_join(join_table, r + lcks.map{|k| [k, SQL::QualifiedIdentifier.new(opts.join_table_alias, k)]}, :table_alias=>dsa)
1135:               end
1136:             end
1137:             ds.all do |assoc_record|
1138:               assoc_record.values.delete(rn) if delete_rn
1139:               hash_key = if uses_lcks
1140:                 left_key_alias.map{|k| assoc_record.values.delete(k)}
1141:               else
1142:                 assoc_record.values.delete(left_key_alias)
1143:               end
1144:               next unless objects = h[hash_key]
1145:               objects.each{|object| object.associations[name].push(assoc_record)}
1146:             end
1147:             if opts.eager_limit_strategy == :ruby
1148:               limit, offset = opts.limit_and_offset
1149:               rows.each{|o| o.associations[name] = o.associations[name].slice(offset||0, limit) || []}
1150:             end
1151:           end
1152:           
1153:           join_type = opts[:graph_join_type]
1154:           select = opts[:graph_select]
1155:           use_only_conditions = opts.include?(:graph_only_conditions)
1156:           only_conditions = opts[:graph_only_conditions]
1157:           conditions = opts[:graph_conditions]
1158:           graph_block = opts[:graph_block]
1159:           use_jt_only_conditions = opts.include?(:graph_join_table_only_conditions)
1160:           jt_only_conditions = opts[:graph_join_table_only_conditions]
1161:           jt_join_type = opts[:graph_join_table_join_type]
1162:           jt_graph_block = opts[:graph_join_table_block]
1163:           opts[:eager_grapher] ||= proc do |eo|
1164:             ds = eo[:self]
1165:             ds = ds.graph(join_table, use_jt_only_conditions ? jt_only_conditions : lcks.zip(lpkcs) + graph_jt_conds, :select=>false, :table_alias=>ds.unused_table_alias(join_table, [eo[:table_alias]]), :join_type=>jt_join_type, :implicit_qualifier=>eo[:implicit_qualifier], :from_self_alias=>ds.opts[:eager_graph][:master], &jt_graph_block)
1166:             ds.graph(eager_graph_dataset(opts, eo), use_only_conditions ? only_conditions : opts.right_primary_keys.zip(rcks) + conditions, :select=>select, :table_alias=>eo[:table_alias], :join_type=>join_type, &graph_block)
1167:           end
1168:       
1169:           def_association_dataset_methods(opts)
1170:       
1171:           return if opts[:read_only]
1172:       
1173:           association_module_private_def(opts._add_method, opts) do |o|
1174:             h = {}
1175:             lcks.zip(lcpks).each{|k, pk| h[k] = send(pk)}
1176:             rcks.zip(opts.right_primary_key_methods).each{|k, pk| h[k] = o.send(pk)}
1177:             _join_table_dataset(opts).insert(h)
1178:           end
1179:           association_module_private_def(opts._remove_method, opts) do |o|
1180:             _join_table_dataset(opts).filter(lcks.zip(lcpks.map{|k| send(k)}) + rcks.zip(opts.right_primary_key_methods.map{|k| o.send(k)})).delete
1181:           end
1182:           association_module_private_def(opts._remove_all_method, opts) do
1183:             _join_table_dataset(opts).filter(lcks.zip(lcpks.map{|k| send(k)})).delete
1184:           end
1185:       
1186:           def_add_method(opts)
1187:           def_remove_methods(opts)
1188:         end
def_many_to_one(opts) click to toggle source

Configures many_to_one association reflection and adds the related association methods

      # File lib/sequel/model/associations.rb, line 1191
1191:         def def_many_to_one(opts)
1192:           name = opts[:name]
1193:           model = self
1194:           opts[:key] = opts.default_key unless opts.include?(:key)
1195:           key_column = key = opts[:key]
1196:           cks = opts[:graph_keys] = opts[:keys] = Array(key)
1197:           if opts[:key_column]
1198:             key_column = opts[:key_column]
1199:             opts[:eager_loader_key] ||= key_column
1200:             opts[:graph_keys] = Array(key_column)
1201:           end
1202:           opts[:qualified_key] = opts.qualify_cur(key)
1203:           if opts[:primary_key]
1204:             cpks = Array(opts[:primary_key])
1205:             raise(Error, "mismatched number of composite keys: #{cks.inspect} vs #{cpks.inspect}") unless cks.length == cpks.length
1206:           end
1207:           uses_cks = opts[:uses_composite_keys] = cks.length > 1
1208:           qualify = opts[:qualify] != false
1209:           opts[:cartesian_product_number] ||= 0
1210:           opts[:dataset] ||= proc do
1211:             klass = opts.associated_class
1212:             klass.filter(Array(opts.qualified_primary_key).zip(cks.map{|k| send(k)}))
1213:           end
1214:           opts[:eager_loader] ||= proc do |eo|
1215:             h = eo[:key_hash][key_column]
1216:             keys = h.keys
1217:             # Default the cached association to nil, so any object that doesn't have it
1218:             # populated will have cached the negative lookup.
1219:             eo[:rows].each{|object| object.associations[name] = nil}
1220:             # Skip eager loading if no objects have a foreign key for this association
1221:             unless keys.empty?
1222:               klass = opts.associated_class
1223:               model.eager_loading_dataset(opts, klass.filter(opts.qualified_primary_key=>keys), nil, eo[:associations], eo).all do |assoc_record|
1224:                 hash_key = uses_cks ? opts.primary_key_methods.map{|k| assoc_record.send(k)} : assoc_record.send(opts.primary_key_method)
1225:                 next unless objects = h[hash_key]
1226:                 objects.each{|object| object.associations[name] = assoc_record}
1227:               end
1228:             end
1229:           end
1230:       
1231:           join_type = opts[:graph_join_type]
1232:           select = opts[:graph_select]
1233:           use_only_conditions = opts.include?(:graph_only_conditions)
1234:           only_conditions = opts[:graph_only_conditions]
1235:           conditions = opts[:graph_conditions]
1236:           graph_block = opts[:graph_block]
1237:           graph_cks = opts[:graph_keys]
1238:           opts[:eager_grapher] ||= proc do |eo|
1239:             ds = eo[:self]
1240:             ds.graph(eager_graph_dataset(opts, eo), use_only_conditions ? only_conditions : opts.primary_keys.zip(graph_cks) + conditions, eo.merge(:select=>select, :join_type=>join_type, :from_self_alias=>ds.opts[:eager_graph][:master]), &graph_block)
1241:           end
1242:       
1243:           def_association_dataset_methods(opts)
1244:           
1245:           return if opts[:read_only]
1246:       
1247:           association_module_private_def(opts._setter_method, opts){|o| cks.zip(opts.primary_key_methods).each{|k, pk| send(:"#{k}=", (o.send(pk) if o))}}
1248:           association_module_def(opts.setter_method, opts){|o| set_associated_object(opts, o)}
1249:         end
def_one_to_many(opts) click to toggle source

Configures one_to_many and one_to_one association reflections and adds the related association methods

      # File lib/sequel/model/associations.rb, line 1252
1252:         def def_one_to_many(opts)
1253:           one_to_one = opts[:type] == :one_to_one
1254:           name = opts[:name]
1255:           model = self
1256:           key = (opts[:key] ||= opts.default_key)
1257:           km = opts[:key_method] ||= opts[:key]
1258:           cks = opts[:keys] = Array(key)
1259:           primary_key = (opts[:primary_key] ||= self.primary_key)
1260:           cpks = opts[:primary_keys] = Array(primary_key)
1261:           pkc = opts[:primary_key_column] ||= primary_key
1262:           pkcs = opts[:primary_key_columns] ||= Array(pkc)
1263:           elk = opts.eager_loader_key
1264:           raise(Error, "mismatched number of composite keys: #{cks.inspect} vs #{cpks.inspect}") unless cks.length == cpks.length
1265:           uses_cks = opts[:uses_composite_keys] = cks.length > 1
1266:           opts[:dataset] ||= proc do
1267:             opts.associated_class.filter(Array(opts.qualified_key).zip(cpks.map{|k| send(k)}))
1268:           end
1269:           opts[:eager_loader] ||= proc do |eo|
1270:             h = eo[:key_hash][elk]
1271:             rows = eo[:rows]
1272:             if one_to_one
1273:               rows.each{|object| object.associations[name] = nil}
1274:             else
1275:               rows.each{|object| object.associations[name] = []}
1276:             end
1277:             reciprocal = opts.reciprocal
1278:             klass = opts.associated_class
1279:             filter_keys = opts.eager_loading_predicate_key
1280:             ds = model.eager_loading_dataset(opts, klass.filter(filter_keys=>h.keys), nil, eo[:associations], eo)
1281:             case opts.eager_limit_strategy
1282:             when :distinct_on
1283:               ds = ds.distinct(*filter_keys).order_prepend(*filter_keys)
1284:             when :window_function
1285:               delete_rn = true
1286:               rn = ds.row_number_column
1287:               ds = apply_window_function_eager_limit_strategy(ds, opts)
1288:             when :correlated_subquery
1289:               ds = apply_correlated_subquery_eager_limit_strategy(ds, opts) do |xds|
1290:                 xds.where(opts.associated_object_keys.map{|k| [SQL::QualifiedIdentifier.new(xds.first_source_alias, k), SQL::QualifiedIdentifier.new(xds.first_source_table, k)]})
1291:               end
1292:             end
1293:             ds.all do |assoc_record|
1294:               assoc_record.values.delete(rn) if delete_rn
1295:               hash_key = uses_cks ? km.map{|k| assoc_record.send(k)} : assoc_record.send(km)
1296:               next unless objects = h[hash_key]
1297:               if one_to_one
1298:                 objects.each do |object| 
1299:                   unless object.associations[name]
1300:                     object.associations[name] = assoc_record
1301:                     assoc_record.associations[reciprocal] = object if reciprocal
1302:                   end
1303:                 end
1304:               else
1305:                 objects.each do |object| 
1306:                   object.associations[name].push(assoc_record)
1307:                   assoc_record.associations[reciprocal] = object if reciprocal
1308:                 end
1309:               end
1310:             end
1311:             if opts.eager_limit_strategy == :ruby
1312:               limit, offset = opts.limit_and_offset
1313:               rows.each{|o| o.associations[name] = o.associations[name].slice(offset||0, limit) || []}
1314:             end
1315:           end
1316:           
1317:           join_type = opts[:graph_join_type]
1318:           select = opts[:graph_select]
1319:           use_only_conditions = opts.include?(:graph_only_conditions)
1320:           only_conditions = opts[:graph_only_conditions]
1321:           conditions = opts[:graph_conditions]
1322:           opts[:cartesian_product_number] ||= one_to_one ? 0 : 1
1323:           graph_block = opts[:graph_block]
1324:           opts[:eager_grapher] ||= proc do |eo|
1325:             ds = eo[:self]
1326:             ds = ds.graph(eager_graph_dataset(opts, eo), use_only_conditions ? only_conditions : cks.zip(pkcs) + conditions, eo.merge(:select=>select, :join_type=>join_type, :from_self_alias=>ds.opts[:eager_graph][:master]), &graph_block)
1327:             # We only load reciprocals for one_to_many associations, as other reciprocals don't make sense
1328:             ds.opts[:eager_graph][:reciprocals][eo[:table_alias]] = opts.reciprocal
1329:             ds
1330:           end
1331:       
1332:           def_association_dataset_methods(opts)
1333:           
1334:           ck_nil_hash ={}
1335:           cks.each{|k| ck_nil_hash[k] = nil}
1336: 
1337:           unless opts[:read_only]
1338:             validate = opts[:validate]
1339: 
1340:             if one_to_one
1341:               association_module_private_def(opts._setter_method, opts) do |o|
1342:                 up_ds = _apply_association_options(opts, opts.associated_class.filter(cks.zip(cpks.map{|k| send(k)})))
1343:                 if o
1344:                   up_ds = up_ds.exclude(o.pk_hash)
1345:                   cks.zip(cpks).each{|k, pk| o.send(:"#{k}=", send(pk))}
1346:                 end
1347:                 checked_transaction do
1348:                   up_ds.update(ck_nil_hash)
1349:                   o.save(:validate=>validate) || raise(Sequel::Error, "invalid associated object, cannot save") if o
1350:                 end
1351:               end
1352:               association_module_def(opts.setter_method, opts){|o| set_one_to_one_associated_object(opts, o)}
1353:             else 
1354:               association_module_private_def(opts._add_method, opts) do |o|
1355:                 cks.zip(cpks).each{|k, pk| o.send(:"#{k}=", send(pk))}
1356:                 o.save(:validate=>validate) || raise(Sequel::Error, "invalid associated object, cannot save")
1357:               end
1358:               def_add_method(opts)
1359:       
1360:               association_module_private_def(opts._remove_method, opts) do |o|
1361:                 cks.each{|k| o.send(:"#{k}=", nil)}
1362:                 o.save(:validate=>validate) || raise(Sequel::Error, "invalid associated object, cannot save")
1363:               end
1364:               association_module_private_def(opts._remove_all_method, opts) do
1365:                 _apply_association_options(opts, opts.associated_class.filter(cks.zip(cpks.map{|k| send(k)}))).update(ck_nil_hash)
1366:               end
1367:               def_remove_methods(opts)
1368:             end
1369:           end
1370:         end
def_one_to_one(opts) click to toggle source

Alias of def_one_to_many, since they share pretty much the same code.

      # File lib/sequel/model/associations.rb, line 1373
1373:         def def_one_to_one(opts)
1374:           def_one_to_many(opts)
1375:         end
def_remove_methods(opts) click to toggle source

Add the remove_ and remove_all instance methods

      # File lib/sequel/model/associations.rb, line 1378
1378:         def def_remove_methods(opts)
1379:           association_module_def(opts.remove_method, opts){|o,*args| remove_associated_object(opts, o, *args)}
1380:           association_module_def(opts.remove_all_method, opts){|*args| remove_all_associated_objects(opts, *args)}
1381:         end
eager_graph_dataset(opts, eager_options) click to toggle source

Return dataset to graph into given the association reflection, applying the :callback option if set.

      # File lib/sequel/model/associations.rb, line 1384
1384:         def eager_graph_dataset(opts, eager_options)
1385:           ds = opts.associated_class.dataset
1386:           if cb = eager_options[:callback]
1387:             ds = cb.call(ds)
1388:           end
1389:           ds
1390:         end

Disabled; run with --debug to generate this.

[Validate]

Generated with the Darkfish Rdoc Generator 1.1.6.