Method: ActiveRecord::Associations::ClassMethods#belongs_to
- Defined in:
- activerecord/lib/active_record/associations.rb
#belongs_to(name, scope = nil, options = {}) ⇒ Object
Specifies a one-to-one association with another class. This method should only be used if this class contains the foreign key. If the other class contains the foreign key, then you should use has_one
instead. See also ActiveRecord::Associations::ClassMethods’s overview on when to use has_one
and when to use belongs_to
.
Methods will be added for retrieval and query for a single associated object, for which this object holds an id:
- association(force_reload = false)
-
Returns the associated object.
nil
is returned if none is found. - association=(associate)
-
Assigns the associate object, extracts the primary key, and sets it as the foreign key.
- build_association(attributes = {})
-
Returns a new object of the associated type that has been instantiated with
attributes
and linked to this object through a foreign key, but has not yet been saved. - create_association(attributes = {})
-
Returns a new object of the associated type that has been instantiated with
attributes
, linked to this object through a foreign key, and that has already been saved (if it passed the validation). - create_association!(attributes = {})
-
Does the same as
create_association
, but raisesActiveRecord::RecordInvalid
if the record is invalid.
(association
is replaced with the symbol passed as the first argument, so belongs_to :author
would add among others author.nil?
.)
Example
A Post class declares belongs_to :author
, which will add:
-
Post#author
(similar toAuthor.find(author_id)
) -
Post#author=(author)
(similar topost.author_id = author.id
) -
Post#build_author
(similar topost.author = Author.new
) -
Post#create_author
(similar topost.author = Author.new; post.author.save; post.author
) -
Post#create_author!
(similar topost.author = Author.new; post.author.save!; post.author
)
The declaration can also include an options hash to specialize the behavior of the association.
Options
- :class_name
-
Specify the class name of the association. Use it only if that name can’t be inferred from the association name. So
belongs_to :author
will by default be linked to the Author class, but if the real class name is Person, you’ll have to specify it with this option. - :foreign_key
-
Specify the foreign key used for the association. By default this is guessed to be the name of the association with an “_id” suffix. So a class that defines a
belongs_to :person
association will use “person_id” as the default:foreign_key
. Similarly,belongs_to :favorite_person, class_name: "Person"
will use a foreign key of “favorite_person_id”. - :foreign_type
-
Specify the column used to store the associated object’s type, if this is a polymorphic association. By default this is guessed to be the name of the association with a “_type” suffix. So a class that defines a
belongs_to :taggable, polymorphic: true
association will use “taggable_type” as the default:foreign_type
. - :primary_key
-
Specify the method that returns the primary key of associated object used for the association. By default this is id.
- :dependent
-
If set to
:destroy
, the associated object is destroyed when this object is. If set to:delete
, the associated object is deleted without calling its destroy method. This option should not be specified whenbelongs_to
is used in conjunction with ahas_many
relationship on another class because of the potential to leave orphaned records behind. - :counter_cache
-
Caches the number of belonging objects on the associate class through the use of
increment_counter
anddecrement_counter
. The counter cache is incremented when an object of this class is created and decremented when it’s destroyed. This requires that a column named#{table_name}_count
(such ascomments_count
for a belonging Comment class) is used on the associate class (such as a Post class) - that is the migration for#{table_name}_count
is created on the associate class (such thatPost.comments_count
will return the count cached, see note below). You can also specify a custom counter cache column by providing a column name instead of atrue
/false
value to this option (e.g.,counter_cache: :my_custom_counter
.) Note: Specifying a counter cache will add it to that model’s list of readonly attributes usingattr_readonly
. - :polymorphic
-
Specify this association is a polymorphic association by passing
true
. Note: If you’ve enabled the counter cache, then you may want to add the counter cache attribute to theattr_readonly
list in the associated classes (e.g.class Post; attr_readonly :comments_count; end
). - :validate
-
If
false
, don’t validate the associated objects when saving the parent object.false
by default. - :autosave
-
If true, always save the associated object or destroy it if marked for destruction, when saving the parent object. If false, never save or destroy the associated object. By default, only save the associated object if it’s a new record.
Note that
accepts_nested_attributes_for
sets:autosave
totrue
. - :touch
-
If true, the associated object will be touched (the updated_at/on attributes set to now) when this record is either saved or destroyed. If you specify a symbol, that attribute will be updated with the current time in addition to the updated_at/on attribute.
- :inverse_of
-
Specifies the name of the
has_one
orhas_many
association on the associated object that is the inverse of thisbelongs_to
association. Does not work in combination with the:polymorphic
options. See ActiveRecord::Associations::ClassMethods’s overview on Bi-directional associations for more detail.
Option examples:
belongs_to :firm, foreign_key: "client_of"
belongs_to :person, primary_key: "name", foreign_key: "person_name"
belongs_to :author, class_name: "Person", foreign_key: "author_id"
belongs_to :valid_coupon, ->(o) { where "discounts > ?", o.payments_count },
class_name: "Coupon", foreign_key: "coupon_id"
belongs_to :attachable, polymorphic: true
belongs_to :project, readonly: true
belongs_to :post, counter_cache: true
belongs_to :company, touch: true
belongs_to :company, touch: :employees_last_updated_at
1432 1433 1434 1435 |
# File 'activerecord/lib/active_record/associations.rb', line 1432 def belongs_to(name, scope = nil, = {}) reflection = Builder::BelongsTo.build(self, name, scope, ) Reflection.add_reflection self, name, reflection end |