module ActiveRecord::Associations::ClassMethods
def belongs_to(name, scope = nil, **options)
belongs_to :account, strict_loading: true
belongs_to :account, default: -> { company.account }
belongs_to :user, optional: true
belongs_to :company, touch: :employees_last_updated_at
belongs_to :comment, touch: true
belongs_to :post, counter_cache: true
belongs_to :project, -> { readonly }
belongs_to :attachable, polymorphic: true
class_name: "Coupon", foreign_key: "coupon_id"
belongs_to :valid_coupon, ->(o) { where "discounts > ?", o.payments_count },
belongs_to :author, class_name: "Person", foreign_key: "author_id"
belongs_to :person, primary_key: "name", foreign_key: "person_name"
belongs_to :firm, foreign_key: "client_of"
Option examples:
When the value is set the Array size must match associated model's primary key or +query_constraints+ size.
This is an optional option. By default Rails will attempt to derive the value automatically.
Serves as a composite foreign key. Defines the list of columns to be used to query the associated object.
[+:query_constraints+]
associated records to be deleted in a background job.
Specifies an instance method to be called on the owner. The method must return true in order for the
[+:ensuring_owner_was+]
Enforces strict loading every time the associated record is loaded through this association.
[+:strict_loading+]
Please note that callable won't be executed if the record exists.
be initialized with a particular record before validation.
Provide a callable (i.e. proc or lambda) to specify that the association should
[+:default+]
you don't want to have association presence validated, use optional: true.
NOTE: required is set to true by default and is deprecated. If
+:inverse_of+ to avoid an extra query during validation.
This will validate the association itself, not the id. You can use
When set to +true+, the association will also have its presence validated.
[+:required+]
When set to +true+, the association will not have its presence validated.
[+:optional+]
for more detail.
See {Bi-directional associations}[rdoc-ref:Associations::ClassMethods@Bi-directional+associations]
object that is the inverse of this #belongs_to association.
Specifies the name of the #has_one or #has_many association on the associated
[+:inverse_of+]
+after_commit+, and +after_rollback+ callbacks will be executed.
Please note that no validation will be performed when touching, and only the +after_touch+,
will be updated with the current time in addition to the +updated_at+ / +updated_on+ attribute.
when this record is either saved or destroyed. If you specify a symbol, that attribute
If true, the associated object will be touched (the +updated_at+ / +updated_on+ attributes set to current time)
[+:touch+]
sets :autosave to true.
Note that NestedAttributes::ClassMethods#accepts_nested_attributes_for
By default, only save the associated object if it's a new record.
If false, never save or destroy the associated object.
saving the parent object.
If true, always save the associated object or destroy it if marked for destruction, when
[+:autosave+]
If you want to ensure associated objects are revalidated on every update, use +validates_associated+.
When set to +true+, validates new objects added to association when saving the parent object. +false+ by default.
[+:validate+]
*_type polymorphic type column of the corresponding rows.
Note: Since polymorphic associations rely on storing class names in the database, make sure to update the class names in the
Specify this association is a polymorphic association by passing +true+.
[+:polymorphic+]
to the +attr_readonly+ list in the associated classes (e.g. class Post; attr_readonly :comments_count; end).
Note: If you've enabled the counter cache, then you may want to add the counter cache attribute
If you also need to specify a custom column name, use counter_cache: { active: false, column: :my_custom_counter }.
use counter_cache: { active: false }.
use the possibly incorrect counter cache column values and always get the results from the database,
counter cache columns updated with the child records creation/removal and to avoid the mentioned methods
counter caches internally, can produce incorrect results). To safely backfill the values while keeping
and before the use of +:counter_cache+ (otherwise methods like +size+/+any?+/etc, which use
values must be backfilled separately of the column addition (to not lock the table for too long)
Starting to use counter caches on existing large tables can be troublesome, because the column
option (e.g., counter_cache: :my_custom_counter.)
cache column by providing a column name instead of a +true+/+false+ value to this
return the count cached). You can also specify a custom counter
#{table_name}_count is created on the associate class (such that Post.comments_count will
is used on the associate class (such as a Post class) - that is the migration for
named #{table_name}_count (such as +comments_count+ for a belonging Comment class)
class is created and decremented when it's destroyed. This requires that a column
and CounterCache::ClassMethods#decrement_counter. The counter cache is incremented when an object of this
Caches the number of belonging objects on the associate class through the use of CounterCache::ClassMethods#increment_counter
[+:counter_cache+]
orphaned records behind.
a #has_many relationship on another class because of the potential to leave
This option should not be specified when #belongs_to is used in conjunction with
:destroy_async, the associated object is scheduled to be destroyed in a background job.
:delete, the associated object is deleted *without* calling its destroy method. If set to
If set to :destroy, the associated object is destroyed when this object is. If set to
[+:dependent+]
By default this is +id+.
Specify the method that returns the primary key of associated object used for the association.
[+:primary_key+]
association will use "taggable_type" as the default :foreign_type.
suffix. So a class that defines a belongs_to :taggable, polymorphic: true
association. By default this is guessed to be the name of the association with a "_type"
Specify the column used to store the associated object's type, if this is a polymorphic
[+:foreign_type+]
inverse, so it is generally a good idea to set the :inverse_of option as well.
Setting the :foreign_key option prevents automatic detection of the association's
of "favorite_person_id".
belongs_to :favorite_person, class_name: "Person" will use a foreign key
association will use "person_id" as the default :foreign_key. Similarly,
of the association with an "_id" suffix. So a class that defines a belongs_to :person
Specify the foreign key used for the association. By default this is guessed to be the name
[+:foreign_key+]
if the real class name is Person, you'll have to specify it with this option.
from the association name. So belongs_to :author will by default be linked to the Author class, but
Specify the class name of the association. Use it only if that name can't be inferred
[+:class_name+]
The declaration can also include an +options+ hash to specialize the behavior of the association.
==== Options
belongs_to :level, ->(game) { where("game_level > ?", game.current_level) }
belongs_to :user, -> { joins(:friends) }
belongs_to :firm, -> { where(id: 2) }
Scope examples:
when you access the associated object.
lambda) to retrieve a specific record or customize the generated query
You can pass a second argument +scope+ as a callable (i.e. proc or
==== Scopes
post.author_previously_changed?
post.author_changed?
post.reset_author
post.reload_author
post.create_author! # similar to post.author = Author.new; post.author.save!; post.author
post.create_author # similar to post.author = Author.new; post.author.save; post.author
post.build_author # similar to post.author = Author.new
post.author = author # similar to post.author_id = author.id
post.author # similar to Author.find(post.author_id)
author = Author.find(19)
post = Post.find(7)
Declaring belongs_to :author adds the following methods (and more):
end
belongs_to :author
class Post < ActiveRecord::Base
==== Example
Returns true if the previous save updated the association to reference a new associate object.
[association_previously_changed?]
Returns true if a new associate object has been assigned and the next save will update the foreign key.
[association_changed?]
Unloads the associated object. The next access will query it from the database.
[reset_association]
Returns the associated object, forcing a database read.
[reload_association]
if the record is invalid.
Does the same as create_association, but raises ActiveRecord::RecordInvalid
[create_association!(attributes = {})]
has already been saved (if it passed the validation).
with +attributes+, linked to this object through a foreign key, and that
Returns a new object of the associated type that has been instantiated
[create_association(attributes = {})]
with +attributes+ and linked to this object through a foreign key, but has not yet been saved.
Returns a new object of the associated type that has been instantiated
[build_association(attributes = {})]
No modification or deletion of existing records takes place.
Assigns the associate object, extracts the primary key, and sets it as the foreign key.
[association=(associate)]
Returns the associated object. +nil+ is returned if none is found.
[association]
belongs_to :author would add among others author.nil?.
+association+ is a placeholder for the symbol passed as the +name+ argument, so
this object holds an id:
Methods will be added for retrieval and query for a single associated object, for which
for more detail on when to use #has_one and when to use #belongs_to.
association?}[rdoc-ref:Associations::ClassMethods@Is+it+a+-23belongs_to+or+-23has_one+association-3F]
instead. See {Is it a belongs_to or has_one
other class contains the foreign key, then you should use #has_one
should only be used if this class contains the foreign key. If the
Specifies a one-to-one association with another class. This method
def belongs_to(name, scope = nil, **options) reflection = Builder::BelongsTo.build(self, name, scope, options) Reflection.add_reflection self, name, reflection end