module 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, use the :adder, :remover, :clearer, and/or :setter options. These options override the default behavior.
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) => #<Sequel::Model::Associations::ManyToOneAssociationReflection Project.many_to_one :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
All association reflections defined for this model (default: {}).
Hash
with column symbol keys and arrays of many_to_one
association symbols that should be cleared when the column value changes.
Whether association metadata should be cached in the association reflection. If not cached, it will be computed on demand. In general you only want to set this to false when using code reloading. When using code reloading, setting this will make sure that if an associated class is removed or modified, this class will not have a reference to the previous class.
The default options to use for all associations. This hash is merged into the association reflection hash for all association reflections.
The default options to use for all associations of a given type. This is a hash keyed by association type symbol. If there is a value for the association type symbol key, the resulting hash will be merged into the association reflection hash for all association reflections of that type.
The default :eager_limit_strategy option to use for limited or offset associations (default: true, causing Sequel
to use what it considers the most appropriate strategy).
Public Instance Methods
Source
# File lib/sequel/model/associations.rb 1621 def all_association_reflections 1622 association_reflections.values 1623 end
Array
of all association reflections for this model class
Source
# File lib/sequel/model/associations.rb 1866 def associate(type, name, opts = OPTS, &block) 1867 raise(Error, 'invalid association type') unless assoc_class = Sequel.synchronize{ASSOCIATION_TYPES[type]} 1868 raise(Error, 'Model.associate name argument must be a symbol') unless name.is_a?(Symbol) 1869 1870 # dup early so we don't modify opts 1871 orig_opts = opts.dup 1872 1873 if opts[:clone] 1874 cloned_assoc = association_reflection(opts[:clone]) 1875 remove_class_name = orig_opts[:class] && !orig_opts[:class_name] 1876 orig_opts = cloned_assoc[:orig_opts].merge(orig_opts) 1877 orig_opts.delete(:class_name) if remove_class_name 1878 end 1879 1880 opts = Hash[default_association_options] 1881 if type_options = default_association_type_options[type] 1882 opts.merge!(type_options) 1883 end 1884 opts.merge!(orig_opts) 1885 opts.merge!(:type => type, :name => name, :cache=>({} if cache_associations), :model => self) 1886 1887 opts[:block] = block if block 1888 opts[:instance_specific] = true if orig_opts[:dataset] 1889 if !opts.has_key?(:instance_specific) && (block || orig_opts[:block]) 1890 # It's possible the association is instance specific, in that it depends on 1891 # values other than the foreign key value. This needs to be checked for 1892 # in certain places to disable optimizations. 1893 opts[:instance_specific] = _association_instance_specific_default(name) 1894 end 1895 if (orig_opts[:instance_specific] || orig_opts[:dataset]) && !opts.has_key?(:allow_eager) && !opts[:eager_loader] 1896 # For associations explicitly marked as instance specific, or that use the 1897 # :dataset option, where :allow_eager is not set, and no :eager_loader is 1898 # provided, disallow eager loading. In these cases, eager loading is 1899 # unlikely to work. This is not done for implicit setting of :instance_specific, 1900 # because implicit use is done by default for all associations with blocks, 1901 # and the vast majority of associations with blocks use the block for filtering 1902 # in a manner compatible with eager loading. 1903 opts[:allow_eager] = false 1904 end 1905 opts = assoc_class.new.merge!(opts) 1906 1907 if opts[:clone] && !opts.cloneable?(cloned_assoc) 1908 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]})") 1909 end 1910 1911 opts[:use_placeholder_loader] = !opts[:instance_specific] && !opts[:eager_graph] unless opts.include?(:use_placeholder_loader) 1912 opts[:eager_block] = opts[:block] unless opts.include?(:eager_block) 1913 opts[:graph_join_type] ||= :left_outer 1914 opts[:order_eager_graph] = true unless opts.include?(:order_eager_graph) 1915 conds = opts[:conditions] 1916 opts[:graph_alias_base] ||= name 1917 opts[:graph_conditions] = conds if !opts.include?(:graph_conditions) and Sequel.condition_specifier?(conds) 1918 opts[:graph_conditions] = opts.fetch(:graph_conditions, []).to_a 1919 opts[:graph_select] = Array(opts[:graph_select]) if opts[:graph_select] 1920 [:before_add, :before_remove, :after_add, :after_remove, :after_load, :before_set, :after_set].each do |cb_type| 1921 opts[cb_type] = Array(opts[cb_type]) if opts[cb_type] 1922 end 1923 1924 if opts[:extend] 1925 opts[:extend] = Array(opts[:extend]) 1926 opts[:reverse_extend] = opts[:extend].reverse 1927 end 1928 1929 late_binding_class_option(opts, opts.returns_array? ? singularize(name) : name) 1930 1931 # Remove :class entry if it exists and is nil, to work with cached_fetch 1932 opts.delete(:class) unless opts[:class] 1933 1934 def_association(opts) 1935 1936 orig_opts.delete(:clone) 1937 opts[:orig_class] = orig_opts[:class] || orig_opts[:class_name] 1938 orig_opts.merge!(:class_name=>opts[:class_name], :class=>opts[:class], :block=>opts[:block]) 1939 opts[:orig_opts] = orig_opts 1940 # don't add to association_reflections until we are sure there are no errors 1941 association_reflections[name] = opts 1942 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.
- :one_through_one
-
Similar to
many_to_many
in terms of foreign keys, but only one object is associated to the current object through the association. Provides only getter methods, no setter or modification methods. - :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 tomany_to_one
, except that theone_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:
Multiple Types¶ ↑
- :adder
-
Proc used to define the private add* method for doing the database work to associate the given object to the current object (*_to_many assocations). Set to nil to not define a add_* method for the association.
- :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
- :allow_eager_graph
-
If set to false, you cannot load the association eagerly via eager_graph.
- :allow_filtering_by
-
If set to false, you cannot use the association when filtering
- :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
,one_to_one
, andone_through_one
associations, 1 forone_to_many
andmany_to_many
associations). - :class
-
The associated class or its name as a string or symbol. If not given, uses the association’s name, which is camelized (and singularized unless the type is :many_to_one, :one_to_one, or
one_through_one
). If this is specified as a string or symbol, you must specify the full class name (e.g. “::SomeModule::MyModel”). - :class_namespace
-
If :class is given as a string or symbol, sets the default namespace in which to look for the class.
class: 'Foo', class_namespace: 'Bar'
looks for::Bar::Foo
.) - :clearer
-
Proc used to define the private remove_all* method for doing the database work to remove all objects associated to the current object (*_to_many assocations). Set to nil to not define a remove_all_* method for the association.
- :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 where. This option is not respected when using eager_graph or association_join, unless it is hash or array of two element arrays. Consider also specifying the :graph_block option if the value for this option is not a hash or array of two element arrays and you plan to use this association in eager_graph or association_join.
- :dataset
-
A proc that is used to define the method to get the base dataset to use (before the other options are applied). If the proc accepts an argument, it is passed the related association reflection. It is a best practice to always have the dataset accept an argument and use the argument to return the appropriate dataset.
- :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 viaeager
. - :eager_grapher
-
A proc to use to implement eager loading via
eager_graph
, overriding the default. Takes an options hash with at least the entries :self (the receiver of the eager_graph call), :table_alias (the alias to use for table to graph into the association), and :implicit_qualifier (the alias that was used for the current table). Should return a copy of the dataset with the association graphed into it. - :eager_limit_strategy
-
Determines the strategy used for enforcing limits and offsets when eager loading associations via the
eager
method. - :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.
- :eager_loading_predicate_transform
-
A callable object with which to transform the predicate key values used when eager loading. Called with two arguments, the array of predicate key values, and a the reflection for the association being eager loaded.
- :extend
-
A module or array of modules to extend the dataset with.
- :filter_limit_strategy
-
Determines the strategy used for enforcing limits and offsets when filtering by limited associations. Possible options are :window_function, :distinct_on, or :correlated_subquery depending on association type and database type.
- :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 viaeager_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 viaeager_graph
, instead of the default conditions specified by the foreign/primary keys. This option causes the :graph_conditions option to be ignored. - :graph_order
-
the order to use when using eager_graph, instead of the default order. This should be used in the case where :order contains an identifier qualified by the table’s name, which may not match the alias used when eager graphing. By setting this to the unqualified identifier, it will be automatically qualified when using eager_graph.
- :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. - :graph_use_association_block
-
Makes eager_graph consider the association block. Without this, eager_graph ignores the bock and only use the :graph_* options.
- :instance_specific
-
Marks the association as instance specific. Should be used if the association block uses instance specific state, or transient state (accessing current date/time, etc.).
- :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.
- :no_association_method
-
Do not add a method for the association. This can save memory if the association method is never used.
- :no_dataset_method
-
Do not add a method for the association dataset. This can save memory if the dataset method is never used.
- :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
orone_to_one
associations), or add_/remove_/remove_all_ methods (forone_to_many
andmany_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. - :remover
-
Proc used to define the private remove* method for doing the database work to remove the association between the given object and the current object (*_to_many assocations). Set to nil to not define a remove_* method for the association.
- :select
-
the columns to select. Defaults to the associated class’s table_name.* in an association that uses joins, 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.
- :setter
-
Proc used to define the private _*= method for doing the work to setup the assocation between the given object and the current object (*_to_one associations). Set to nil to not define a setter method for the association.
- :subqueries_per_union
-
The number of subqueries to use in each UNION query, for eager loading limited associations using the default :union strategy.
- :use_placeholder_loader
-
Whether to use a placeholder loader when eager loading the association. Can be set to false to disable the use of a placeholder loader if one would be used by default.
- :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 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 qualified 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 model method differs from the primary key column, in conjunction with defining a model alias method for the primary key column.
- :raise_on_save_failure
-
Do not raise exceptions for hook or validation failures when saving associated objects in the add/remove methods (return nil instead) [one_to_many only].
:many_to_many and :one_through_one¶ ↑
- :graph_join_table_block
-
The block to pass to
join_table
for the join table when eagerly loading the association viaeager_graph
. - :graph_join_table_conditions
-
The additional conditions to use on the
SQL
join for the join table when eagerly loading the association viaeager_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 viaeager_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 viaeager_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.
- :join_table_db
-
When retrieving records when using lazy loading or eager loading via
eager
, instead of a join between to the join table and the associated table, use a separate query for the join table using the givenDatabase
object. - :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 1945 def association_reflection(name) 1946 association_reflections[name] 1947 end
The association reflection hash for the association of the given name.
Source
# File lib/sequel/model/associations.rb 1950 def associations 1951 association_reflections.keys 1952 end
Array
of association name symbols
Source
# File lib/sequel/model/associations.rb 1955 def eager_load_results(opts, eo, &block) 1956 opts.eager_load_results(eo, &block) 1957 end
Eager load the association with the given eager loader options.
Source
# File lib/sequel/model/associations.rb 1974 def finalize_associations 1975 @association_reflections.each_value(&:finalize) 1976 end
Finalize all associations such that values that are looked up dynamically in associated classes are set statically. As this modifies the associations, it must be done before calling freeze.
Source
# File lib/sequel/model/associations.rb 1960 def freeze 1961 @association_reflections.freeze.each_value(&:freeze) 1962 @autoreloading_associations.freeze.each_value(&:freeze) 1963 @default_association_options.freeze 1964 @default_association_type_options.freeze 1965 @default_association_type_options.each_value(&:freeze) 1966 1967 super 1968 end
Freeze association related metadata when freezing model class.
Source
# File lib/sequel/model/associations.rb 1979 def many_to_many(name, opts=OPTS, &block) 1980 associate(:many_to_many, name, opts, &block) 1981 end
Shortcut for adding a many_to_many
association, see associate
Source
# File lib/sequel/model/associations.rb 1984 def many_to_one(name, opts=OPTS, &block) 1985 associate(:many_to_one, name, opts, &block) 1986 end
Shortcut for adding a many_to_one
association, see associate
Source
# File lib/sequel/model/associations.rb 1989 def one_through_one(name, opts=OPTS, &block) 1990 associate(:one_through_one, name, opts, &block) 1991 end
Shortcut for adding a one_through_one
association, see associate
Source
# File lib/sequel/model/associations.rb 1994 def one_to_many(name, opts=OPTS, &block) 1995 associate(:one_to_many, name, opts, &block) 1996 end
Shortcut for adding a one_to_many
association, see associate
Source
# File lib/sequel/model/associations.rb 1999 def one_to_one(name, opts=OPTS, &block) 2000 associate(:one_to_one, name, opts, &block) 2001 end
Shortcut for adding a one_to_one
association, see associate
Private Instance Methods
Source
# File lib/sequel/model/associations.rb 2010 def _association_instance_specific_default(_) 2011 true 2012 end
The default value for the instance_specific option, if the association could be instance specific and the :instance_specific option is not specified.
Source
# File lib/sequel/model/associations.rb 2016 def association_module(opts=OPTS) 2017 opts.fetch(:methods_module, overridable_methods_module) 2018 end
The module to use for the association’s methods. Defaults to the overridable_methods_module.
Source
# File lib/sequel/model/associations.rb 2023 def association_module_def(name, opts=OPTS, &block) 2024 mod = association_module(opts) 2025 mod.send(:define_method, name, &block) 2026 mod.send(:alias_method, name, name) 2027 end
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.
Source
# File lib/sequel/model/associations.rb 2033 def association_module_delegate_def(name, opts, &block) 2034 mod = association_module(opts) 2035 mod.send(:define_method, name, &block) 2036 # :nocov: 2037 mod.send(:ruby2_keywords, name) if mod.respond_to?(:ruby2_keywords, true) 2038 # :nocov: 2039 mod.send(:alias_method, name, name) 2040 end
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. This method allows passing keywords through the defined methods.
Source
# File lib/sequel/model/associations.rb 2043 def association_module_private_def(name, opts=OPTS, &block) 2044 association_module_def(name, opts, &block) 2045 association_module(opts).send(:private, name) 2046 end
Add a private method to the module included in the class.
Source
# File lib/sequel/model/associations.rb 2050 def def_association(opts) 2051 send(:"def_#{opts[:type]}", opts) 2052 def_association_instance_methods(opts) 2053 end
Delegate to the type-specific association method to setup the association, and define the association instance methods.
Source
# File lib/sequel/model/associations.rb 2063 def def_association_instance_methods(opts) 2064 # Always set the method names in the association reflection, even if they 2065 # are not used, for backwards compatibility. 2066 opts[:dataset_method] = :"#{opts[:name]}_dataset" 2067 if opts.returns_array? 2068 sname = singularize(opts[:name]) 2069 opts[:_add_method] = :"_add_#{sname}" 2070 opts[:add_method] = :"add_#{sname}" 2071 opts[:_remove_method] = :"_remove_#{sname}" 2072 opts[:remove_method] = :"remove_#{sname}" 2073 opts[:_remove_all_method] = :"_remove_all_#{opts[:name]}" 2074 opts[:remove_all_method] = :"remove_all_#{opts[:name]}" 2075 else 2076 opts[:_setter_method] = :"_#{opts[:name]}=" 2077 opts[:setter_method] = :"#{opts[:name]}=" 2078 end 2079 2080 association_module_def(opts.dataset_method, opts){_dataset(opts)} unless opts[:no_dataset_method] 2081 if opts[:block] 2082 opts[:block_method] = Plugins.def_sequel_method(association_module(opts), "#{opts[:name]}_block", 1, &opts[:block]) 2083 end 2084 opts[:dataset_opt_arity] = opts[:dataset].arity == 0 ? 0 : 1 2085 opts[:dataset_opt_method] = Plugins.def_sequel_method(association_module(opts), "#{opts[:name]}_dataset_opt", opts[:dataset_opt_arity], &opts[:dataset]) 2086 def_association_method(opts) unless opts[:no_association_method] 2087 2088 return if opts[:read_only] 2089 2090 if opts[:setter] && opts[:_setter] 2091 # This is backwards due to backwards compatibility 2092 association_module_private_def(opts[:_setter_method], opts, &opts[:setter]) 2093 association_module_def(opts[:setter_method], opts, &opts[:_setter]) 2094 end 2095 2096 if adder = opts[:adder] 2097 association_module_private_def(opts[:_add_method], opts, &adder) 2098 association_module_delegate_def(opts[:add_method], opts){|o,*args| add_associated_object(opts, o, *args)} 2099 end 2100 2101 if remover = opts[:remover] 2102 association_module_private_def(opts[:_remove_method], opts, &remover) 2103 association_module_delegate_def(opts[:remove_method], opts){|o,*args| remove_associated_object(opts, o, *args)} 2104 end 2105 2106 if clearer = opts[:clearer] 2107 association_module_private_def(opts[:_remove_all_method], opts, &clearer) 2108 association_module_delegate_def(opts[:remove_all_method], opts){|*args| remove_all_associated_objects(opts, *args)} 2109 end 2110 end
Define all of the association instance methods for this association.
Source
# File lib/sequel/model/associations.rb 2056 def def_association_method(opts) 2057 association_module_def(opts.association_method, opts) do |dynamic_opts=OPTS, &block| 2058 load_associated_objects(opts, dynamic_opts, &block) 2059 end 2060 end
Adds the association method to the association methods module.
Source
# File lib/sequel/model/associations.rb 2113 def def_many_to_many(opts) 2114 one_through_one = opts[:type] == :one_through_one 2115 left = (opts[:left_key] ||= opts.default_left_key) 2116 lcks = opts[:left_keys] = Array(left) 2117 right = (opts[:right_key] ||= opts.default_right_key) 2118 rcks = opts[:right_keys] = Array(right) 2119 left_pk = (opts[:left_primary_key] ||= self.primary_key) 2120 opts[:eager_loader_key] = left_pk unless opts.has_key?(:eager_loader_key) 2121 lcpks = opts[:left_primary_keys] = Array(left_pk) 2122 lpkc = opts[:left_primary_key_column] ||= left_pk 2123 lpkcs = opts[:left_primary_key_columns] ||= Array(lpkc) 2124 raise(Error, "mismatched number of left keys: #{lcks.inspect} vs #{lcpks.inspect}") unless lcks.length == lcpks.length 2125 if opts[:right_primary_key] 2126 rcpks = Array(opts[:right_primary_key]) 2127 raise(Error, "mismatched number of right keys: #{rcks.inspect} vs #{rcpks.inspect}") unless rcks.length == rcpks.length 2128 end 2129 opts[:uses_left_composite_keys] = lcks.length > 1 2130 uses_rcks = opts[:uses_right_composite_keys] = rcks.length > 1 2131 opts[:cartesian_product_number] ||= one_through_one ? 0 : 1 2132 join_table = (opts[:join_table] ||= opts.default_join_table) 2133 opts[:left_key_alias] ||= opts.default_associated_key_alias 2134 opts[:graph_join_table_join_type] ||= opts[:graph_join_type] 2135 if opts[:uniq] 2136 opts[:after_load] ||= [] 2137 opts[:after_load].unshift(:array_uniq!) 2138 end 2139 if join_table_db = opts[:join_table_db] 2140 opts[:use_placeholder_loader] = false 2141 opts[:allow_eager_graph] = false 2142 opts[:allow_filtering_by] = false 2143 opts[:eager_limit_strategy] = nil 2144 join_table_ds = join_table_db.from(join_table) 2145 opts[:dataset] ||= proc do |r| 2146 vals = join_table_ds.where(lcks.zip(lcpks.map{|k| get_column_value(k)})).select_map(right) 2147 ds = r.associated_dataset.where(opts.right_primary_key => vals) 2148 if uses_rcks 2149 vals.delete_if{|v| v.any?(&:nil?)} 2150 else 2151 vals.delete(nil) 2152 end 2153 ds = ds.clone(:no_results=>true) if vals.empty? 2154 ds 2155 end 2156 opts[:eager_loader] ||= proc do |eo| 2157 h = eo[:id_map] 2158 assign_singular = opts.assign_singular? 2159 rpk = opts.right_primary_key 2160 name = opts[:name] 2161 2162 join_map = join_table_ds.where(left=>h.keys).select_hash_groups(right, left) 2163 2164 if uses_rcks 2165 join_map.delete_if{|v,| v.any?(&:nil?)} 2166 else 2167 join_map.delete(nil) 2168 end 2169 2170 eo = Hash[eo] 2171 2172 if join_map.empty? 2173 eo[:no_results] = true 2174 else 2175 join_map.each_value do |vs| 2176 vs.replace(vs.flat_map{|v| h[v]}) 2177 vs.uniq! 2178 end 2179 2180 eo[:loader] = false 2181 eo[:right_keys] = join_map.keys 2182 end 2183 2184 opts[:model].eager_load_results(opts, eo) do |assoc_record| 2185 rpkv = if uses_rcks 2186 assoc_record.values.values_at(*rpk) 2187 else 2188 assoc_record.values[rpk] 2189 end 2190 2191 objects = join_map[rpkv] 2192 2193 if assign_singular 2194 objects.each do |object| 2195 object.associations[name] ||= assoc_record 2196 end 2197 else 2198 objects.each do |object| 2199 object.associations[name].push(assoc_record) 2200 end 2201 end 2202 end 2203 end 2204 else 2205 opts[:dataset] ||= opts.association_dataset_proc 2206 opts[:eager_loader] ||= opts.method(:default_eager_loader) 2207 end 2208 2209 join_type = opts[:graph_join_type] 2210 select = opts[:graph_select] 2211 use_only_conditions = opts.include?(:graph_only_conditions) 2212 only_conditions = opts[:graph_only_conditions] 2213 conditions = opts[:graph_conditions] 2214 graph_block = opts[:graph_block] 2215 graph_jt_conds = opts[:graph_join_table_conditions] = opts.fetch(:graph_join_table_conditions, []).to_a 2216 use_jt_only_conditions = opts.include?(:graph_join_table_only_conditions) 2217 jt_only_conditions = opts[:graph_join_table_only_conditions] 2218 jt_join_type = opts[:graph_join_table_join_type] 2219 jt_graph_block = opts[:graph_join_table_block] 2220 opts[:eager_grapher] ||= proc do |eo| 2221 ds = eo[:self] 2222 egls = eo[:limit_strategy] 2223 if egls && egls != :ruby 2224 associated_key_array = opts.associated_key_array 2225 orig_egds = egds = eager_graph_dataset(opts, eo) 2226 egds = egds. 2227 inner_join(join_table, rcks.zip(opts.right_primary_keys) + graph_jt_conds, :qualify=>:deep). 2228 select_all(egds.first_source). 2229 select_append(*associated_key_array) 2230 egds = opts.apply_eager_graph_limit_strategy(egls, egds) 2231 ds.graph(egds, associated_key_array.map(&:alias).zip(lpkcs) + conditions, :qualify=>:deep, :table_alias=>eo[:table_alias], :implicit_qualifier=>eo[:implicit_qualifier], :join_type=>eo[:join_type]||join_type, :from_self_alias=>eo[:from_self_alias], :join_only=>eo[:join_only], :select=>select||orig_egds.columns, &graph_block) 2232 else 2233 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=>eo[:join_type]||jt_join_type, :join_only=>eo[:join_only], :implicit_qualifier=>eo[:implicit_qualifier], :qualify=>:deep, :from_self_alias=>eo[:from_self_alias], &jt_graph_block) 2234 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], :qualify=>:deep, :join_type=>eo[:join_type]||join_type, :join_only=>eo[:join_only], &graph_block) 2235 end 2236 end 2237 2238 return if opts[:read_only] 2239 2240 if one_through_one 2241 unless opts.has_key?(:setter) 2242 opts[:setter] = proc do |o| 2243 h = {} 2244 lh = lcks.zip(lcpks.map{|k| get_column_value(k)}) 2245 jtds = _join_table_dataset(opts).where(lh) 2246 2247 checked_transaction do 2248 current = jtds.first 2249 2250 if o 2251 new_values = [] 2252 rcks.zip(opts.right_primary_key_methods).each{|k, pk| new_values << (h[k] = o.get_column_value(pk))} 2253 end 2254 2255 if current 2256 current_values = rcks.map{|k| current[k]} 2257 jtds = jtds.where(rcks.zip(current_values)) 2258 if o 2259 if current_values != new_values 2260 jtds.update(h) 2261 end 2262 else 2263 jtds.delete 2264 end 2265 elsif o 2266 lh.each{|k,v| h[k] = v} 2267 jtds.insert(h) 2268 end 2269 end 2270 end 2271 end 2272 if opts.fetch(:setter, true) 2273 opts[:_setter] = proc{|o| set_one_through_one_associated_object(opts, o)} 2274 end 2275 else 2276 unless opts.has_key?(:adder) 2277 opts[:adder] = proc do |o| 2278 h = {} 2279 lcks.zip(lcpks).each{|k, pk| h[k] = get_column_value(pk)} 2280 rcks.zip(opts.right_primary_key_methods).each{|k, pk| h[k] = o.get_column_value(pk)} 2281 _join_table_dataset(opts).insert(h) 2282 end 2283 end 2284 2285 unless opts.has_key?(:remover) 2286 opts[:remover] = proc do |o| 2287 _join_table_dataset(opts).where(lcks.zip(lcpks.map{|k| get_column_value(k)}) + rcks.zip(opts.right_primary_key_methods.map{|k| o.get_column_value(k)})).delete 2288 end 2289 end 2290 2291 unless opts.has_key?(:clearer) 2292 opts[:clearer] = proc do 2293 _join_table_dataset(opts).where(lcks.zip(lcpks.map{|k| get_column_value(k)})).delete 2294 end 2295 end 2296 end 2297 end
Configures many_to_many
and one_through_one
association reflection and adds the related association methods
Source
# File lib/sequel/model/associations.rb 2300 def def_many_to_one(opts) 2301 name = opts[:name] 2302 opts[:key] = opts.default_key unless opts.has_key?(:key) 2303 key = opts[:key] 2304 opts[:eager_loader_key] = key unless opts.has_key?(:eager_loader_key) 2305 cks = opts[:graph_keys] = opts[:keys] = Array(key) 2306 opts[:key_column] ||= key 2307 opts[:graph_keys] = opts[:key_columns] = Array(opts[:key_column]) 2308 opts[:qualified_key] = opts.qualify_cur(key) 2309 if opts[:primary_key] 2310 cpks = Array(opts[:primary_key]) 2311 raise(Error, "mismatched number of keys: #{cks.inspect} vs #{cpks.inspect}") unless cks.length == cpks.length 2312 end 2313 uses_cks = opts[:uses_composite_keys] = cks.length > 1 2314 opts[:cartesian_product_number] ||= 0 2315 2316 if !opts.has_key?(:many_to_one_pk_lookup) && 2317 (opts[:dataset] || opts[:conditions] || opts[:block] || opts[:select] || 2318 (opts.has_key?(:key) && opts[:key] == nil)) 2319 opts[:many_to_one_pk_lookup] = false 2320 end 2321 auto_assocs = @autoreloading_associations 2322 cks.each do |k| 2323 (auto_assocs[k] ||= []) << name 2324 end 2325 2326 opts[:dataset] ||= opts.association_dataset_proc 2327 opts[:eager_loader] ||= proc do |eo| 2328 h = eo[:id_map] 2329 pk_meths = opts.primary_key_methods 2330 2331 eager_load_results(opts, eo) do |assoc_record| 2332 hash_key = uses_cks ? pk_meths.map{|k| assoc_record.get_column_value(k)} : assoc_record.get_column_value(opts.primary_key_method) 2333 h[hash_key].each{|object| object.associations[name] = assoc_record} 2334 end 2335 end 2336 2337 join_type = opts[:graph_join_type] 2338 select = opts[:graph_select] 2339 use_only_conditions = opts.include?(:graph_only_conditions) 2340 only_conditions = opts[:graph_only_conditions] 2341 conditions = opts[:graph_conditions] 2342 graph_block = opts[:graph_block] 2343 graph_cks = opts[:graph_keys] 2344 opts[:eager_grapher] ||= proc do |eo| 2345 ds = eo[:self] 2346 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=>eo[:join_type]||join_type, :qualify=>:deep), &graph_block) 2347 end 2348 2349 return if opts[:read_only] 2350 2351 unless opts.has_key?(:setter) 2352 opts[:setter] = proc{|o| cks.zip(opts.primary_key_methods).each{|k, pk| set_column_value(:"#{k}=", (o.get_column_value(pk) if o))}} 2353 end 2354 if opts.fetch(:setter, true) 2355 opts[:_setter] = proc{|o| set_associated_object(opts, o)} 2356 end 2357 end
Configures many_to_one
association reflection and adds the related association methods
Source
# File lib/sequel/model/associations.rb 2481 def def_one_through_one(opts) 2482 def_many_to_many(opts) 2483 end
Alias of def_many_to_many
, since they share pretty much the same code.
Source
# File lib/sequel/model/associations.rb 2360 def def_one_to_many(opts) 2361 one_to_one = opts[:type] == :one_to_one 2362 name = opts[:name] 2363 key = (opts[:key] ||= opts.default_key) 2364 km = opts[:key_method] ||= opts[:key] 2365 cks = opts[:keys] = Array(key) 2366 opts[:key_methods] = Array(opts[:key_method]) 2367 primary_key = (opts[:primary_key] ||= self.primary_key) 2368 opts[:eager_loader_key] = primary_key unless opts.has_key?(:eager_loader_key) 2369 cpks = opts[:primary_keys] = Array(primary_key) 2370 pkc = opts[:primary_key_column] ||= primary_key 2371 pkcs = opts[:primary_key_columns] ||= Array(pkc) 2372 raise(Error, "mismatched number of keys: #{cks.inspect} vs #{cpks.inspect}") unless cks.length == cpks.length 2373 uses_cks = opts[:uses_composite_keys] = cks.length > 1 2374 opts[:dataset] ||= opts.association_dataset_proc 2375 opts[:eager_loader] ||= proc do |eo| 2376 h = eo[:id_map] 2377 reciprocal = opts.reciprocal 2378 assign_singular = opts.assign_singular? 2379 delete_rn = opts.delete_row_number_column 2380 2381 eager_load_results(opts, eo) do |assoc_record| 2382 assoc_record.values.delete(delete_rn) if delete_rn 2383 hash_key = uses_cks ? km.map{|k| assoc_record.get_column_value(k)} : assoc_record.get_column_value(km) 2384 objects = h[hash_key] 2385 if assign_singular 2386 objects.each do |object| 2387 unless object.associations[name] 2388 object.associations[name] = assoc_record 2389 assoc_record.associations[reciprocal] = object if reciprocal 2390 end 2391 end 2392 else 2393 objects.each do |object| 2394 object.associations[name].push(assoc_record) 2395 assoc_record.associations[reciprocal] = object if reciprocal 2396 end 2397 end 2398 end 2399 end 2400 2401 join_type = opts[:graph_join_type] 2402 select = opts[:graph_select] 2403 use_only_conditions = opts.include?(:graph_only_conditions) 2404 only_conditions = opts[:graph_only_conditions] 2405 conditions = opts[:graph_conditions] 2406 opts[:cartesian_product_number] ||= one_to_one ? 0 : 1 2407 graph_block = opts[:graph_block] 2408 opts[:eager_grapher] ||= proc do |eo| 2409 ds = eo[:self] 2410 ds = ds.graph(opts.apply_eager_graph_limit_strategy(eo[:limit_strategy], eager_graph_dataset(opts, eo)), use_only_conditions ? only_conditions : cks.zip(pkcs) + conditions, eo.merge(:select=>select, :join_type=>eo[:join_type]||join_type, :qualify=>:deep), &graph_block) 2411 # We only load reciprocals for one_to_many associations, as other reciprocals don't make sense 2412 ds.opts[:eager_graph][:reciprocals][eo[:table_alias]] = opts.reciprocal 2413 ds 2414 end 2415 2416 return if opts[:read_only] 2417 2418 save_opts = {:validate=>opts[:validate]} 2419 ck_nil_hash ={} 2420 cks.each{|k| ck_nil_hash[k] = nil} 2421 2422 if one_to_one 2423 unless opts.has_key?(:setter) 2424 opts[:setter] = proc do |o| 2425 up_ds = _apply_association_options(opts, opts.associated_dataset.where(cks.zip(cpks.map{|k| get_column_value(k)}))) 2426 2427 if (froms = up_ds.opts[:from]) && (from = froms[0]) && (from.is_a?(Sequel::Dataset) || (from.is_a?(Sequel::SQL::AliasedExpression) && from.expression.is_a?(Sequel::Dataset))) 2428 if old = up_ds.first 2429 cks.each{|k| old.set_column_value(:"#{k}=", nil)} 2430 end 2431 save_old = true 2432 end 2433 2434 if o 2435 if !o.new? && !save_old 2436 up_ds = up_ds.exclude(o.pk_hash) 2437 end 2438 cks.zip(cpks).each{|k, pk| o.set_column_value(:"#{k}=", get_column_value(pk))} 2439 end 2440 2441 checked_transaction do 2442 if save_old 2443 old.save(save_opts) || raise(Sequel::Error, "invalid previously associated object, cannot save") if old 2444 else 2445 up_ds.skip_limit_check.update(ck_nil_hash) 2446 end 2447 2448 o.save(save_opts) || raise(Sequel::Error, "invalid associated object, cannot save") if o 2449 end 2450 end 2451 end 2452 if opts.fetch(:setter, true) 2453 opts[:_setter] = proc{|o| set_one_to_one_associated_object(opts, o)} 2454 end 2455 else 2456 save_opts[:raise_on_failure] = opts[:raise_on_save_failure] != false 2457 2458 unless opts.has_key?(:adder) 2459 opts[:adder] = proc do |o| 2460 cks.zip(cpks).each{|k, pk| o.set_column_value(:"#{k}=", get_column_value(pk))} 2461 o.save(save_opts) 2462 end 2463 end 2464 2465 unless opts.has_key?(:remover) 2466 opts[:remover] = proc do |o| 2467 cks.each{|k| o.set_column_value(:"#{k}=", nil)} 2468 o.save(save_opts) 2469 end 2470 end 2471 2472 unless opts.has_key?(:clearer) 2473 opts[:clearer] = proc do 2474 _apply_association_options(opts, opts.associated_dataset.where(cks.zip(cpks.map{|k| get_column_value(k)}))).update(ck_nil_hash) 2475 end 2476 end 2477 end 2478 end
Configures one_to_many
and one_to_one
association reflections and adds the related association methods
Source
# File lib/sequel/model/associations.rb 2486 def def_one_to_one(opts) 2487 def_one_to_many(opts) 2488 end
Alias of def_one_to_many
, since they share pretty much the same code.
Source
# File lib/sequel/model/associations.rb 2491 def eager_graph_dataset(opts, eager_options) 2492 ds = opts.associated_class.dataset 2493 if opts[:graph_use_association_block] && (b = opts[:block]) 2494 ds = b.call(ds) 2495 end 2496 if cb = eager_options[:callback] 2497 ds = cb.call(ds) 2498 end 2499 ds 2500 end
Return dataset to graph into given the association reflection, applying the :callback option if set.
Source
# File lib/sequel/model/associations.rb 2504 def reload_db_schema? 2505 !@cache_associations 2506 end
If not caching associations, reload the database schema by default, ignoring any cached values.