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 |
| 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.
Methods
Public Instance
- all_association_reflections
- associate
- association_reflection
- association_reflections
- associations
- autoreloading_associations
- cache_associations
- default_association_options
- default_association_type_options
- default_eager_limit_strategy
- eager_load_results
- finalize_associations
- freeze
- many_to_many
- many_to_one
- one_through_one
- one_to_many
- one_to_one
Attributes
| association_reflections | [R] |
All association reflections defined for this model (default: {}). |
| autoreloading_associations | [R] |
Hash with column symbol keys and arrays of |
| cache_associations | [RW] |
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. |
| default_association_options | [RW] |
The default options to use for all associations. This hash is merged into the association reflection hash for all association reflections. |
| default_association_type_options | [RW] |
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. |
| default_eager_limit_strategy | [RW] |
The default :eager_limit_strategy option to use for limited or offset associations (default: true, causing |
Public Instance methods
Array of all association reflections for this model class
# File lib/sequel/model/associations.rb 1793 def all_association_reflections 1794 association_reflections.values 1795 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 |
| :one_to_one |
Similar to |
| :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 |
| :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 |
| :class_namespace |
If :class is given as a string or symbol, sets the default namespace in which to look for the class. |
| :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_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_grapher |
A proc to use to implement eager loading via |
| :eager_limit_strategy |
Determines the strategy used for enforcing limits and offsets when eager loading associations via the |
| :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, |
| :graph_block |
The block to pass to join_table when eagerly loading the association via |
| :graph_conditions |
The additional conditions to use on the |
| :graph_join_type |
The type of |
| :graph_only_conditions |
The conditions to use on the |
| :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 |
| :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 |
| :read_only |
Do not add a setter method (for |
| :reciprocal |
the symbol name of the reciprocal association, if it exists. By default, |
| :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 |
| :graph_join_table_conditions |
The additional conditions to use on the |
| :graph_join_table_join_type |
The type of |
| :graph_join_table_only_conditions |
The conditions to use on the |
| :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 |
| :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 2038 def associate(type, name, opts = OPTS, &block) 2039 raise(Error, 'invalid association type') unless assoc_class = Sequel.synchronize{ASSOCIATION_TYPES[type]} 2040 raise(Error, 'Model.associate name argument must be a symbol') unless name.is_a?(Symbol) 2041 2042 # dup early so we don't modify opts 2043 orig_opts = opts.dup 2044 2045 if opts[:clone] 2046 cloned_assoc = association_reflection(opts[:clone]) 2047 remove_class_name = orig_opts[:class] && !orig_opts[:class_name] 2048 orig_opts = cloned_assoc[:orig_opts].merge(orig_opts) 2049 orig_opts.delete(:class_name) if remove_class_name 2050 end 2051 2052 opts = Hash[default_association_options] 2053 if type_options = default_association_type_options[type] 2054 opts.merge!(type_options) 2055 end 2056 opts.merge!(orig_opts) 2057 opts.merge!(:type => type, :name => name, :cache=>({} if cache_associations), :model => self) 2058 2059 opts[:block] = block if block 2060 opts[:instance_specific] = true if orig_opts[:dataset] 2061 if !opts.has_key?(:instance_specific) && (block || orig_opts[:block]) 2062 # It's possible the association is instance specific, in that it depends on 2063 # values other than the foreign key value. This needs to be checked for 2064 # in certain places to disable optimizations. 2065 opts[:instance_specific] = _association_instance_specific_default(name) 2066 end 2067 if (orig_opts[:instance_specific] || orig_opts[:dataset]) && !opts.has_key?(:allow_eager) && !opts[:eager_loader] 2068 # For associations explicitly marked as instance specific, or that use the 2069 # :dataset option, where :allow_eager is not set, and no :eager_loader is 2070 # provided, disallow eager loading. In these cases, eager loading is 2071 # unlikely to work. This is not done for implicit setting of :instance_specific, 2072 # because implicit use is done by default for all associations with blocks, 2073 # and the vast majority of associations with blocks use the block for filtering 2074 # in a manner compatible with eager loading. 2075 opts[:allow_eager] = false 2076 end 2077 opts = assoc_class.new.merge!(opts) 2078 2079 if opts[:clone] && !opts.cloneable?(cloned_assoc) 2080 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]})") 2081 end 2082 2083 opts[:use_placeholder_loader] = !opts[:instance_specific] && !opts[:eager_graph] unless opts.include?(:use_placeholder_loader) 2084 opts[:eager_block] = opts[:block] unless opts.include?(:eager_block) 2085 opts[:graph_join_type] ||= :left_outer 2086 opts[:order_eager_graph] = true unless opts.include?(:order_eager_graph) 2087 conds = opts[:conditions] 2088 opts[:graph_alias_base] ||= name 2089 opts[:graph_conditions] = conds if !opts.include?(:graph_conditions) and Sequel.condition_specifier?(conds) 2090 opts[:graph_conditions] = opts.fetch(:graph_conditions, []).to_a 2091 opts[:graph_select] = Array(opts[:graph_select]) if opts[:graph_select] 2092 [:before_add, :before_remove, :after_add, :after_remove, :after_load, :before_set, :after_set].each do |cb_type| 2093 opts[cb_type] = Array(opts[cb_type]) if opts[cb_type] 2094 end 2095 2096 if opts[:extend] 2097 opts[:extend] = Array(opts[:extend]) 2098 opts[:reverse_extend] = opts[:extend].reverse 2099 end 2100 2101 late_binding_class_option(opts, opts.returns_array? ? singularize(name) : name) 2102 2103 # Remove :class entry if it exists and is nil, to work with cached_fetch 2104 opts.delete(:class) unless opts[:class] 2105 2106 opts[:_hash] = [self, name].hash 2107 2108 def_association(opts) 2109 2110 orig_opts.delete(:clone) 2111 opts[:orig_class] = orig_opts[:class] || orig_opts[:class_name] 2112 orig_opts.merge!(:class_name=>opts[:class_name], :class=>opts[:class], :block=>opts[:block]) 2113 opts[:orig_opts] = orig_opts 2114 # don't add to association_reflections until we are sure there are no errors 2115 association_reflections[name] = opts 2116 end
The association reflection hash for the association of the given name.
# File lib/sequel/model/associations.rb 2119 def association_reflection(name) 2120 association_reflections[name] 2121 end
Array of association name symbols
# File lib/sequel/model/associations.rb 2124 def associations 2125 association_reflections.keys 2126 end
Eager load the association with the given eager loader options.
# File lib/sequel/model/associations.rb 2129 def eager_load_results(opts, eo, &block) 2130 opts.eager_load_results(eo, &block) 2131 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 2148 def finalize_associations 2149 @association_reflections.each_value(&:finalize) 2150 end
Freeze association related metadata when freezing model class.
# File lib/sequel/model/associations.rb 2134 def freeze 2135 @association_reflections.freeze.each_value(&:freeze) 2136 @autoreloading_associations.freeze.each_value(&:freeze) 2137 @default_association_options.freeze 2138 @default_association_type_options.freeze 2139 @default_association_type_options.each_value(&:freeze) 2140 2141 super 2142 end
Shortcut for adding a many_to_many association, see associate
# File lib/sequel/model/associations.rb 2153 def many_to_many(name, opts=OPTS, &block) 2154 associate(:many_to_many, name, opts, &block) 2155 end
Shortcut for adding a many_to_one association, see associate
# File lib/sequel/model/associations.rb 2158 def many_to_one(name, opts=OPTS, &block) 2159 associate(:many_to_one, name, opts, &block) 2160 end
Shortcut for adding a one_through_one association, see associate
# File lib/sequel/model/associations.rb 2163 def one_through_one(name, opts=OPTS, &block) 2164 associate(:one_through_one, name, opts, &block) 2165 end
Shortcut for adding a one_to_many association, see associate
# File lib/sequel/model/associations.rb 2168 def one_to_many(name, opts=OPTS, &block) 2169 associate(:one_to_many, name, opts, &block) 2170 end
Shortcut for adding a one_to_one association, see associate
# File lib/sequel/model/associations.rb 2173 def one_to_one(name, opts=OPTS, &block) 2174 associate(:one_to_one, name, opts, &block) 2175 end