Active Record Associations - Ruby on Rails Guides - 0 views
-
With Active Record associations, we can streamline these - and other - operations by declaratively telling Rails that there is a connection between the two models.
- ...195 more annotations...
-
Associations are implemented using macro-style calls, so that you can declaratively add features to your models
-
A belongs_to association sets up a one-to-one connection with another model, such that each instance of the declaring model "belongs to" one instance of the other model.
-
A has_one association also sets up a one-to-one connection with another model, but with somewhat different semantics (and consequences).
-
This association indicates that each instance of a model contains or possesses one instance of another model
-
This association indicates that each instance of the model has zero or more instances of another model.
-
A has_many :through association is often used to set up a many-to-many connection with another model
-
This association indicates that the declaring model can be matched with zero or more instances of another model by proceeding through a third model.
-
new join models are created for newly associated objects, and if some are gone their rows are deleted.
-
The has_many :through association is also useful for setting up "shortcuts" through nested has_many associations
-
A has_one :through association sets up a one-to-one connection with another model. This association indicates that the declaring model can be matched with one instance of another model by proceeding through a third model.
-
A has_and_belongs_to_many association creates a direct many-to-many connection with another model, with no intervening model.
-
declare a many-to-many relationship is to use has_many :through. This makes the association indirectly, through a join model
-
set up a has_many :through relationship if you need to work with the relationship model as an independent entity
-
set up a has_and_belongs_to_many relationship (though you'll need to remember to create the joining table in the database).
-
With polymorphic associations, a model can belong to more than one other model, on a single association.
-
-
Controlling caching Avoiding name collisions Updating the schema Controlling association scope Bi-directional associations
-
All of the association methods are built around caching, which keeps the result of the most recent query available for further operations.
-
it is a bad idea to give an association a name that is already used for an instance method of ActiveRecord::Base. The association method would override the base method and break things.
-
If you create an association some time after you build the underlying model, you need to remember to create an add_column migration to provide the necessary foreign key.
-
So a join between customer and order models will give the default join table name of "customers_orders" because "c" outranks "o" in lexical ordering.
-
For example, one would expect the tables "paper_boxes" and "papers" to generate a join table name of "papers_paper_boxes" because of the length of the name "paper_boxes", but it in fact generates a join table name of "paper_boxes_papers" (because the underscore '' is lexicographically _less than 's' in common encodings).
-
To associate a model with a model in a different namespace, you must specify the complete class name in your association declaration:
-
-
Every association will attempt to automatically find the inverse association and set the :inverse_of option heuristically (based on the association name)
-
In all of these methods, association is replaced with the symbol passed as the first argument to belongs_to.
-
The association method returns the associated object, if any. If no associated object is found, it returns nil.
-
Behind the scenes, this means extracting the primary key from the associate object and setting this object's foreign key to the same value.
-
once it passes all of the validations specified on the associated model, the associated object will be saved
-
:autosave :class_name :counter_cache :dependent :foreign_key :inverse_of :polymorphic :touch :validate
-
Although the :counter_cache option is specified on the model that includes the belongs_to declaration, the actual column must be added to the associated model.
-
The :inverse_of option specifies the name of the has_many or has_one association that is the inverse of this association
-
set the :touch option to :true, then the updated_at or updated_on timestamp on the associated object will be set to the current time whenever this object is saved or destroyed
-
If you set the :validate option to true, then associated objects will be validated whenever you save this object
-
The select method lets you override the SQL SELECT clause that is used to retrieve data about the associated object
-
Assigning an object to a belongs_to association does not automatically save the object. It does not save the associated object either.
-
:as :autosave :class_name :dependent :foreign_key :inverse_of :primary_key :source :source_type :through :validate
-
It's necessary not to set or leave :nullify option for those associations that have NOT NULL database constraints.
-
The :source_type option specifies the source association type for a has_one :through association that proceeds through a polymorphic association.
-
When you assign an object to a has_one association, that object is automatically saved (in order to update its foreign key).
-
If either of these saves fails due to validation errors, then the assignment statement returns false and the assignment itself is cancelled.
-
If the parent object (the one declaring the has_one association) is unsaved (that is, new_record? returns true) then the child objects are not saved.
-
If you want to assign an object to a has_one association without saving the object, use the association.build method
-
collection(force_reload = false) collection<<(object, ...) collection.delete(object, ...) collection.destroy(object, ...) collection=(objects) collection_singular_ids collection_singular_ids=(ids) collection.clear collection.empty? collection.size collection.find(...) collection.where(...) collection.exists?(...) collection.build(attributes = {}, ...) collection.create(attributes = {}) collection.create!(attributes = {})
-
In all of these methods, collection is replaced with the symbol passed as the first argument to has_many, and collection_singular is replaced with the singularized version of that symbol.
-
The collection<< method adds one or more objects to the collection by setting their foreign keys to the primary key of the calling model
-
The collection.delete method removes one or more objects from the collection by setting their foreign keys to NULL.
-
objects will be destroyed if they're associated with dependent: :destroy, and deleted if they're associated with dependent: :delete_all
-
The collection.destroy method removes one or more objects from the collection by running destroy on each object.
-
The collection_singular_ids= method makes the collection contain only the objects identified by the supplied primary key values, by adding and deleting as appropriate
-
The default strategy for has_many :through associations is delete_all, and for has_many associations is to set the foreign keys to NULL.
-
The collection.clear method removes all objects from the collection according to the strategy specified by the dependent option
-
The collection.where method finds objects within the collection based on the conditions supplied but the objects are loaded lazily meaning that the database is queried only when the object(s) are accessed.
-
The collection.build method returns one or more new objects of the associated type. These objects will be instantiated from the passed attributes, and the link through their foreign key will be created, but the associated objects will not yet be saved.
-
The collection.create method returns a new object of the associated type. This object will be instantiated from the passed attributes, the link through its foreign key will be created, and, once it passes all of the validations specified on the associated model, the associated object will be saved.
-
:as :autosave :class_name :dependent :foreign_key :inverse_of :primary_key :source :source_type :through :validate
-
:delete_all causes all the associated objects to be deleted directly from the database (so callbacks will not execute)
-
By convention, Rails assumes that the column used to hold the primary key of the association is id. You can override this and explicitly specify the primary key with the :primary_key option.
-
You only need to use this option if the name of the source association cannot be automatically inferred from the association name.
-
The :source_type option specifies the source association type for a has_many :through association that proceeds through a polymorphic association.
-
If you use a hash-style where option, then record creation via this association will be automatically scoped using the hash
-
The group method supplies an attribute name to group the result set by, using a GROUP BY clause in the finder SQL.
-
has_many :line_items, -> { group 'orders.id' }, through: :orders
-
The limit method lets you restrict the total number of objects that will be fetched through an association.
-
The order method dictates the order in which associated objects will be received (in the syntax used by an SQL ORDER BY clause).
-
If you want to make sure that, upon insertion, all of the records in the persisted association are distinct (so that you can be sure that when you inspect the association that you will never find duplicate records), you should add a unique index on the table itself
-
When you assign an object to a has_many association, that object is automatically saved (in order to update its foreign key).
-
If any of these saves fails due to validation errors, then the assignment statement returns false and the assignment itself is cancelled.
-
If the parent object (the one declaring the has_many association) is unsaved (that is, new_record? returns true) then the child objects are not saved when they are added
-
assign an object to a has_many association without saving the object, use the collection.build method
-
collection(force_reload = false) collection<<(object, ...) collection.delete(object, ...) collection.destroy(object, ...) collection=(objects) collection_singular_ids collection_singular_ids=(ids) collection.clear collection.empty? collection.size collection.find(...) collection.where(...) collection.exists?(...) collection.build(attributes = {}) collection.create(attributes = {}) collection.create!(attributes = {})
-
If the join table for a has_and_belongs_to_many association has additional columns beyond the two foreign keys, these columns will be added as attributes to records retrieved via that association.
-
If you require this sort of complex behavior on the table that joins two models in a many-to-many relationship, you should use a has_many :through association instead of has_and_belongs_to_many.
-
The collection.delete method removes one or more objects from the collection by deleting records in the join table
-
The collection.destroy method removes one or more objects from the collection by running destroy on each record in the join table, including running callbacks.
-
The collection.clear method removes every object from the collection by deleting the rows from the joining table.
-
The collection.find method finds objects within the collection. It uses the same syntax and options as ActiveRecord::Base.find.
-
The collection.where method finds objects within the collection based on the conditions supplied but the objects are loaded lazily meaning that the database is queried only when the object(s) are accessed.
-
The collection.exists? method checks whether an object meeting the supplied conditions exists in the collection.
-
The :foreign_key and :association_foreign_key options are useful when setting up a many-to-many self-join.
-
Rails assumes that the column in the join table used to hold the foreign key pointing to the other model is the name of that model with the suffix _id added.
-
If you set the :autosave option to true, Rails will save any loaded members and destroy members that are marked for destruction whenever you save the parent object.
-
By convention, Rails assumes that the column in the join table used to hold the foreign key pointing to this model is the name of this model with the suffix _id added.
-
In this case, using @parts.assemblies.create or @parts.assemblies.build will create orders where the factory column has the value "Seattle"
-
If you use a hash-style where, then record creation via this association will be automatically scoped using the hash
-
assign an object to a has_and_belongs_to_many association, that object is automatically saved (in order to update the join table).
-
If any of these saves fails due to validation errors, then the assignment statement returns false and the assignment itself is cancelled.
-
If the parent object (the one declaring the has_and_belongs_to_many association) is unsaved (that is, new_record? returns true) then the child objects are not saved when they are added.
-
If you want to assign an object to a has_and_belongs_to_many association without saving the object, use the collection.build method.
-
Normal callbacks hook into the life cycle of Active Record objects, allowing you to work with those objects at various points
-
if a before_remove callback throws an exception, the object does not get removed from the collection