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
Array
of all association reflections for this model class
# File lib/sequel/model/associations.rb 1547 def all_association_reflections 1548 association_reflections.values 1549 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).
- :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
,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).
- :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 instance_execed 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.
- :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.
- :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
-
Over 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. - :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
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).
- :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).
- :subqueries_per_union
-
The number of subqueries to use in each UNION query, for eager loading limited associations using the default :union strategy.
- :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.
- :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 1768 def associate(type, name, opts = OPTS, &block) 1769 raise(Error, 'invalid association type') unless assoc_class = Sequel.synchronize{ASSOCIATION_TYPES[type]} 1770 raise(Error, 'Model.associate name argument must be a symbol') unless name.is_a?(Symbol) 1771 1772 # dup early so we don't modify opts 1773 orig_opts = opts.dup 1774 1775 if opts[:clone] 1776 cloned_assoc = association_reflection(opts[:clone]) 1777 orig_opts = cloned_assoc[:orig_opts].merge(orig_opts) 1778 end 1779 1780 opts = Hash[default_association_options] 1781 if type_options = default_association_type_options[type] 1782 opts.merge!(type_options) 1783 end 1784 opts.merge!(orig_opts) 1785 opts.merge!(:type => type, :name => name, :cache=>({} if cache_associations), :model => self) 1786 1787 opts[:block] = block if block 1788 if !opts.has_key?(:instance_specific) && (block || orig_opts[:block] || orig_opts[:dataset]) 1789 # It's possible the association is instance specific, in that it depends on 1790 # values other than the foreign key value. This needs to be checked for 1791 # in certain places to disable optimizations. 1792 opts[:instance_specific] = true 1793 end 1794 opts = assoc_class.new.merge!(opts) 1795 1796 if opts[:clone] && !opts.cloneable?(cloned_assoc) 1797 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]})") 1798 end 1799 1800 opts[:eager_block] = opts[:block] unless opts.include?(:eager_block) 1801 opts[:graph_join_type] ||= :left_outer 1802 opts[:order_eager_graph] = true unless opts.include?(:order_eager_graph) 1803 conds = opts[:conditions] 1804 opts[:graph_alias_base] ||= name 1805 opts[:graph_conditions] = conds if !opts.include?(:graph_conditions) and Sequel.condition_specifier?(conds) 1806 opts[:graph_conditions] = opts.fetch(:graph_conditions, []).to_a 1807 opts[:graph_select] = Array(opts[:graph_select]) if opts[:graph_select] 1808 [:before_add, :before_remove, :after_add, :after_remove, :after_load, :before_set, :after_set].each do |cb_type| 1809 opts[cb_type] = Array(opts[cb_type]) if opts[cb_type] 1810 end 1811 1812 if opts[:extend] 1813 opts[:extend] = Array(opts[:extend]) 1814 opts[:reverse_extend] = opts[:extend].reverse 1815 end 1816 1817 late_binding_class_option(opts, opts.returns_array? ? singularize(name) : name) 1818 1819 # Remove :class entry if it exists and is nil, to work with cached_fetch 1820 opts.delete(:class) unless opts[:class] 1821 1822 send(:"def_#{type}", opts) 1823 def_association_instance_methods(opts) 1824 1825 orig_opts.delete(:clone) 1826 opts[:orig_class] = orig_opts[:class] || orig_opts[:class_name] 1827 orig_opts.merge!(:class_name=>opts[:class_name], :class=>opts[:class], :block=>opts[:block]) 1828 opts[:orig_opts] = orig_opts 1829 # don't add to association_reflections until we are sure there are no errors 1830 association_reflections[name] = opts 1831 end
The association reflection hash for the association of the given name.
# File lib/sequel/model/associations.rb 1834 def association_reflection(name) 1835 association_reflections[name] 1836 end
Array
of association name symbols
# File lib/sequel/model/associations.rb 1839 def associations 1840 association_reflections.keys 1841 end
Eager load the association with the given eager loader options.
# File lib/sequel/model/associations.rb 1844 def eager_load_results(opts, eo, &block) 1845 opts.eager_load_results(eo, &block) 1846 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.
# File lib/sequel/model/associations.rb 1863 def finalize_associations 1864 @association_reflections.each_value(&:finalize) 1865 end
Freeze association related metadata when freezing model class.
# File lib/sequel/model/associations.rb 1849 def freeze 1850 @association_reflections.freeze.each_value(&:freeze) 1851 @autoreloading_associations.freeze.each_value(&:freeze) 1852 @default_association_options.freeze 1853 @default_association_type_options.freeze 1854 @default_association_type_options.each_value(&:freeze) 1855 1856 super 1857 end
Shortcut for adding a many_to_many
association, see associate
# File lib/sequel/model/associations.rb 1868 def many_to_many(name, opts=OPTS, &block) 1869 associate(:many_to_many, name, opts, &block) 1870 end
Shortcut for adding a many_to_one
association, see associate
# File lib/sequel/model/associations.rb 1873 def many_to_one(name, opts=OPTS, &block) 1874 associate(:many_to_one, name, opts, &block) 1875 end
Shortcut for adding a one_through_one
association, see associate
# File lib/sequel/model/associations.rb 1878 def one_through_one(name, opts=OPTS, &block) 1879 associate(:one_through_one, name, opts, &block) 1880 end
Shortcut for adding a one_to_many
association, see associate
# File lib/sequel/model/associations.rb 1883 def one_to_many(name, opts=OPTS, &block) 1884 associate(:one_to_many, name, opts, &block) 1885 end
Shortcut for adding a one_to_one
association, see associate
# File lib/sequel/model/associations.rb 1888 def one_to_one(name, opts=OPTS, &block) 1889 associate(:one_to_one, name, opts, &block) 1890 end
Private Instance Methods
The module to use for the association's methods. Defaults to the overridable_methods_module.
# File lib/sequel/model/associations.rb 1899 def association_module(opts=OPTS) 1900 opts.fetch(:methods_module, overridable_methods_module) 1901 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.
# File lib/sequel/model/associations.rb 1906 def association_module_def(name, opts=OPTS, &block) 1907 association_module(opts).module_eval{define_method(name, &block)} 1908 end
Add a private method to the module included in the class.
# File lib/sequel/model/associations.rb 1911 def association_module_private_def(name, opts=OPTS, &block) 1912 association_module_def(name, opts, &block) 1913 association_module(opts).send(:private, name) 1914 end
Define all of the association instance methods for this association.
# File lib/sequel/model/associations.rb 1924 def def_association_instance_methods(opts) 1925 # Always set the method names in the association reflection, even if they 1926 # are not used, for backwards compatibility. 1927 opts[:dataset_method] = :"#{opts[:name]}_dataset" 1928 if opts.returns_array? 1929 sname = singularize(opts[:name]) 1930 opts[:_add_method] = :"_add_#{sname}" 1931 opts[:add_method] = :"add_#{sname}" 1932 opts[:_remove_method] = :"_remove_#{sname}" 1933 opts[:remove_method] = :"remove_#{sname}" 1934 opts[:_remove_all_method] = :"_remove_all_#{opts[:name]}" 1935 opts[:remove_all_method] = :"remove_all_#{opts[:name]}" 1936 else 1937 opts[:_setter_method] = :"_#{opts[:name]}=" 1938 opts[:setter_method] = :"#{opts[:name]}=" 1939 end 1940 1941 association_module_def(opts.dataset_method, opts){_dataset(opts)} 1942 def_association_method(opts) 1943 1944 return if opts[:read_only] 1945 1946 if opts[:setter] && opts[:_setter] 1947 # This is backwards due to backwards compatibility 1948 association_module_private_def(opts[:_setter_method], opts, &opts[:setter]) 1949 association_module_def(opts[:setter_method], opts, &opts[:_setter]) 1950 end 1951 1952 if adder = opts[:adder] 1953 association_module_private_def(opts[:_add_method], opts, &adder) 1954 association_module_def(opts[:add_method], opts){|o,*args| add_associated_object(opts, o, *args)} 1955 end 1956 1957 if remover = opts[:remover] 1958 association_module_private_def(opts[:_remove_method], opts, &remover) 1959 association_module_def(opts[:remove_method], opts){|o,*args| remove_associated_object(opts, o, *args)} 1960 end 1961 1962 if clearer = opts[:clearer] 1963 association_module_private_def(opts[:_remove_all_method], opts, &clearer) 1964 association_module_def(opts[:remove_all_method], opts){|*args| remove_all_associated_objects(opts, *args)} 1965 end 1966 end
Adds the association method to the association methods module.
# File lib/sequel/model/associations.rb 1917 def def_association_method(opts) 1918 association_module_def(opts.association_method, opts) do |dynamic_opts=OPTS, &block| 1919 load_associated_objects(opts, dynamic_opts, &block) 1920 end 1921 end
Configures many_to_many
and one_through_one
association reflection and adds the related association methods
# File lib/sequel/model/associations.rb 1969 def def_many_to_many(opts) 1970 one_through_one = opts[:type] == :one_through_one 1971 left = (opts[:left_key] ||= opts.default_left_key) 1972 lcks = opts[:left_keys] = Array(left) 1973 right = (opts[:right_key] ||= opts.default_right_key) 1974 rcks = opts[:right_keys] = Array(right) 1975 left_pk = (opts[:left_primary_key] ||= self.primary_key) 1976 opts[:eager_loader_key] = left_pk unless opts.has_key?(:eager_loader_key) 1977 lcpks = opts[:left_primary_keys] = Array(left_pk) 1978 lpkc = opts[:left_primary_key_column] ||= left_pk 1979 lpkcs = opts[:left_primary_key_columns] ||= Array(lpkc) 1980 raise(Error, "mismatched number of left keys: #{lcks.inspect} vs #{lcpks.inspect}") unless lcks.length == lcpks.length 1981 if opts[:right_primary_key] 1982 rcpks = Array(opts[:right_primary_key]) 1983 raise(Error, "mismatched number of right keys: #{rcks.inspect} vs #{rcpks.inspect}") unless rcks.length == rcpks.length 1984 end 1985 opts[:uses_left_composite_keys] = lcks.length > 1 1986 opts[:uses_right_composite_keys] = rcks.length > 1 1987 opts[:cartesian_product_number] ||= one_through_one ? 0 : 1 1988 join_table = (opts[:join_table] ||= opts.default_join_table) 1989 opts[:left_key_alias] ||= opts.default_associated_key_alias 1990 opts[:graph_join_table_join_type] ||= opts[:graph_join_type] 1991 if opts[:uniq] 1992 opts[:after_load] ||= [] 1993 opts[:after_load].unshift(:array_uniq!) 1994 end 1995 opts[:dataset] ||= opts.association_dataset_proc 1996 opts[:eager_loader] ||= opts.method(:default_eager_loader) 1997 1998 join_type = opts[:graph_join_type] 1999 select = opts[:graph_select] 2000 use_only_conditions = opts.include?(:graph_only_conditions) 2001 only_conditions = opts[:graph_only_conditions] 2002 conditions = opts[:graph_conditions] 2003 graph_block = opts[:graph_block] 2004 graph_jt_conds = opts[:graph_join_table_conditions] = opts.fetch(:graph_join_table_conditions, []).to_a 2005 use_jt_only_conditions = opts.include?(:graph_join_table_only_conditions) 2006 jt_only_conditions = opts[:graph_join_table_only_conditions] 2007 jt_join_type = opts[:graph_join_table_join_type] 2008 jt_graph_block = opts[:graph_join_table_block] 2009 opts[:eager_grapher] ||= proc do |eo| 2010 ds = eo[:self] 2011 egls = eo[:limit_strategy] 2012 if egls && egls != :ruby 2013 associated_key_array = opts.associated_key_array 2014 orig_egds = egds = eager_graph_dataset(opts, eo) 2015 egds = egds. 2016 inner_join(join_table, rcks.zip(opts.right_primary_keys) + graph_jt_conds, :qualify=>:deep). 2017 select_all(egds.first_source). 2018 select_append(*associated_key_array) 2019 egds = opts.apply_eager_graph_limit_strategy(egls, egds) 2020 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) 2021 else 2022 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) 2023 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) 2024 end 2025 end 2026 2027 return if opts[:read_only] 2028 2029 if one_through_one 2030 opts[:setter] ||= proc do |o| 2031 h = {} 2032 lh = lcks.zip(lcpks.map{|k| get_column_value(k)}) 2033 jtds = _join_table_dataset(opts).where(lh) 2034 2035 checked_transaction do 2036 current = jtds.first 2037 2038 if o 2039 new_values = [] 2040 rcks.zip(opts.right_primary_key_methods).each{|k, pk| new_values << (h[k] = o.get_column_value(pk))} 2041 end 2042 2043 if current 2044 current_values = rcks.map{|k| current[k]} 2045 jtds = jtds.where(rcks.zip(current_values)) 2046 if o 2047 if current_values != new_values 2048 jtds.update(h) 2049 end 2050 else 2051 jtds.delete 2052 end 2053 elsif o 2054 lh.each{|k,v| h[k] = v} 2055 jtds.insert(h) 2056 end 2057 end 2058 end 2059 opts[:_setter] = proc{|o| set_one_through_one_associated_object(opts, o)} 2060 else 2061 opts[:adder] ||= proc do |o| 2062 h = {} 2063 lcks.zip(lcpks).each{|k, pk| h[k] = get_column_value(pk)} 2064 rcks.zip(opts.right_primary_key_methods).each{|k, pk| h[k] = o.get_column_value(pk)} 2065 _join_table_dataset(opts).insert(h) 2066 end 2067 2068 opts[:remover] ||= proc do |o| 2069 _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 2070 end 2071 2072 opts[:clearer] ||= proc do 2073 _join_table_dataset(opts).where(lcks.zip(lcpks.map{|k| get_column_value(k)})).delete 2074 end 2075 end 2076 end
Configures many_to_one
association reflection and adds the related association methods
# File lib/sequel/model/associations.rb 2079 def def_many_to_one(opts) 2080 name = opts[:name] 2081 opts[:key] = opts.default_key unless opts.has_key?(:key) 2082 key = opts[:key] 2083 opts[:eager_loader_key] = key unless opts.has_key?(:eager_loader_key) 2084 cks = opts[:graph_keys] = opts[:keys] = Array(key) 2085 opts[:key_column] ||= key 2086 opts[:graph_keys] = opts[:key_columns] = Array(opts[:key_column]) 2087 opts[:qualified_key] = opts.qualify_cur(key) 2088 if opts[:primary_key] 2089 cpks = Array(opts[:primary_key]) 2090 raise(Error, "mismatched number of keys: #{cks.inspect} vs #{cpks.inspect}") unless cks.length == cpks.length 2091 end 2092 uses_cks = opts[:uses_composite_keys] = cks.length > 1 2093 opts[:cartesian_product_number] ||= 0 2094 2095 if !opts.has_key?(:many_to_one_pk_lookup) && 2096 (opts[:dataset] || opts[:conditions] || opts[:block] || opts[:select] || 2097 (opts.has_key?(:key) && opts[:key] == nil)) 2098 opts[:many_to_one_pk_lookup] = false 2099 end 2100 auto_assocs = @autoreloading_associations 2101 cks.each do |k| 2102 (auto_assocs[k] ||= []) << name 2103 end 2104 2105 opts[:dataset] ||= opts.association_dataset_proc 2106 opts[:eager_loader] ||= proc do |eo| 2107 h = eo[:id_map] 2108 pk_meths = opts.primary_key_methods 2109 2110 eager_load_results(opts, eo) do |assoc_record| 2111 hash_key = uses_cks ? pk_meths.map{|k| assoc_record.get_column_value(k)} : assoc_record.get_column_value(opts.primary_key_method) 2112 if objects = h[hash_key] 2113 objects.each{|object| object.associations[name] = assoc_record} 2114 end 2115 end 2116 end 2117 2118 join_type = opts[:graph_join_type] 2119 select = opts[:graph_select] 2120 use_only_conditions = opts.include?(:graph_only_conditions) 2121 only_conditions = opts[:graph_only_conditions] 2122 conditions = opts[:graph_conditions] 2123 graph_block = opts[:graph_block] 2124 graph_cks = opts[:graph_keys] 2125 opts[:eager_grapher] ||= proc do |eo| 2126 ds = eo[:self] 2127 ds.graph(eager_graph_dataset(opts, eo), use_only_conditions ? only_conditions : opts.primary_keys.zip(graph_cks) + conditions, Hash[eo].merge!(:select=>select, :join_type=>eo[:join_type]||join_type, :qualify=>:deep, :from_self_alias=>eo[:from_self_alias]), &graph_block) 2128 end 2129 2130 return if opts[:read_only] 2131 2132 opts[:setter] ||= proc{|o| cks.zip(opts.primary_key_methods).each{|k, pk| set_column_value(:"#{k}=", (o.get_column_value(pk) if o))}} 2133 opts[:_setter] = proc{|o| set_associated_object(opts, o)} 2134 end
Alias of def_many_to_many
, since they share pretty much the same code.
# File lib/sequel/model/associations.rb 2232 def def_one_through_one(opts) 2233 def_many_to_many(opts) 2234 end
Configures one_to_many
and one_to_one
association reflections and adds the related association methods
# File lib/sequel/model/associations.rb 2137 def def_one_to_many(opts) 2138 one_to_one = opts[:type] == :one_to_one 2139 name = opts[:name] 2140 key = (opts[:key] ||= opts.default_key) 2141 km = opts[:key_method] ||= opts[:key] 2142 cks = opts[:keys] = Array(key) 2143 opts[:key_methods] = Array(opts[:key_method]) 2144 primary_key = (opts[:primary_key] ||= self.primary_key) 2145 opts[:eager_loader_key] = primary_key unless opts.has_key?(:eager_loader_key) 2146 cpks = opts[:primary_keys] = Array(primary_key) 2147 pkc = opts[:primary_key_column] ||= primary_key 2148 pkcs = opts[:primary_key_columns] ||= Array(pkc) 2149 raise(Error, "mismatched number of keys: #{cks.inspect} vs #{cpks.inspect}") unless cks.length == cpks.length 2150 uses_cks = opts[:uses_composite_keys] = cks.length > 1 2151 opts[:dataset] ||= opts.association_dataset_proc 2152 opts[:eager_loader] ||= proc do |eo| 2153 h = eo[:id_map] 2154 reciprocal = opts.reciprocal 2155 assign_singular = opts.assign_singular? 2156 delete_rn = opts.delete_row_number_column 2157 2158 eager_load_results(opts, eo) do |assoc_record| 2159 assoc_record.values.delete(delete_rn) if delete_rn 2160 hash_key = uses_cks ? km.map{|k| assoc_record.get_column_value(k)} : assoc_record.get_column_value(km) 2161 next unless objects = h[hash_key] 2162 if assign_singular 2163 objects.each do |object| 2164 unless object.associations[name] 2165 object.associations[name] = assoc_record 2166 assoc_record.associations[reciprocal] = object if reciprocal 2167 end 2168 end 2169 else 2170 objects.each do |object| 2171 object.associations[name].push(assoc_record) 2172 assoc_record.associations[reciprocal] = object if reciprocal 2173 end 2174 end 2175 end 2176 end 2177 2178 join_type = opts[:graph_join_type] 2179 select = opts[:graph_select] 2180 use_only_conditions = opts.include?(:graph_only_conditions) 2181 only_conditions = opts[:graph_only_conditions] 2182 conditions = opts[:graph_conditions] 2183 opts[:cartesian_product_number] ||= one_to_one ? 0 : 1 2184 graph_block = opts[:graph_block] 2185 opts[:eager_grapher] ||= proc do |eo| 2186 ds = eo[:self] 2187 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, Hash[eo].merge!(:select=>select, :join_type=>eo[:join_type]||join_type, :qualify=>:deep, :from_self_alias=>eo[:from_self_alias]), &graph_block) 2188 # We only load reciprocals for one_to_many associations, as other reciprocals don't make sense 2189 ds.opts[:eager_graph][:reciprocals][eo[:table_alias]] = opts.reciprocal 2190 ds 2191 end 2192 2193 return if opts[:read_only] 2194 2195 save_opts = {:validate=>opts[:validate]} 2196 ck_nil_hash ={} 2197 cks.each{|k| ck_nil_hash[k] = nil} 2198 2199 if one_to_one 2200 opts[:setter] ||= proc do |o| 2201 up_ds = _apply_association_options(opts, opts.associated_dataset.where(cks.zip(cpks.map{|k| get_column_value(k)}))) 2202 if o 2203 up_ds = up_ds.exclude(o.pk_hash) unless o.new? 2204 cks.zip(cpks).each{|k, pk| o.set_column_value(:"#{k}=", get_column_value(pk))} 2205 end 2206 checked_transaction do 2207 up_ds.skip_limit_check.update(ck_nil_hash) 2208 o.save(save_opts) || raise(Sequel::Error, "invalid associated object, cannot save") if o 2209 end 2210 end 2211 opts[:_setter] = proc{|o| set_one_to_one_associated_object(opts, o)} 2212 else 2213 save_opts[:raise_on_failure] = opts[:raise_on_save_failure] != false 2214 2215 opts[:adder] ||= proc do |o| 2216 cks.zip(cpks).each{|k, pk| o.set_column_value(:"#{k}=", get_column_value(pk))} 2217 o.save(save_opts) 2218 end 2219 2220 opts[:remover] ||= proc do |o| 2221 cks.each{|k| o.set_column_value(:"#{k}=", nil)} 2222 o.save(save_opts) 2223 end 2224 2225 opts[:clearer] ||= proc do 2226 _apply_association_options(opts, opts.associated_dataset.where(cks.zip(cpks.map{|k| get_column_value(k)}))).update(ck_nil_hash) 2227 end 2228 end 2229 end
Alias of def_one_to_many
, since they share pretty much the same code.
# File lib/sequel/model/associations.rb 2237 def def_one_to_one(opts) 2238 def_one_to_many(opts) 2239 end
Return dataset to graph into given the association reflection, applying the :callback option if set.
# File lib/sequel/model/associations.rb 2242 def eager_graph_dataset(opts, eager_options) 2243 ds = opts.associated_class.dataset 2244 if cb = eager_options[:callback] 2245 ds = cb.call(ds) 2246 end 2247 ds 2248 end
If not caching associations, reload the database schema by default, ignoring any cached values.
# File lib/sequel/model/associations.rb 2252 def reload_db_schema? 2253 !@cache_associations 2254 end