module ActiveRecord::Associations::ClassMethods
def has_one(name, scope = nil, **options)
has_one :credit_card, required: true
has_one :primary_address, -> { where(primary: true) }, through: :addressables, source: :addressable
has_one :club, through: :membership, disable_joins: true
has_one :club, through: :membership
has_one :boss, -> { readonly }
has_one :attachment, as: :attachable
has_one :project_manager, -> { where(role: 'project_manager') }, class_name: "Person"
has_one :last_comment, -> { order('posted_on') }, class_name: "Comment"
# key value to NULL rather than destroying it
has_one :credit_card, dependent: :nullify # updates the associated records foreign
has_one :credit_card, dependent: :destroy # destroys the associated credit card
Option examples:
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]
+: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]
See ActiveRecord::Associations::ClassMethods's overview on Bi-directional associations for more detail.
that is the inverse of this #has_one association.
Specifies the name of the #belongs_to association on the associated object
[:inverse_of]
:autosave to true.
Note that NestedAttributes::ClassMethods#accepts_nested_attributes_for sets
By default, only save the associated object if it's a new record.
when saving the parent object. If false, never save or destroy the associated object.
If true, always save the associated object or destroy it if marked for destruction,
[: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]
association is a polymorphic #belongs_to.
Specifies type of the source association used by #has_one :through queries where the source
[:source_type]
:favorite on Favorite, unless a :source is given.
has_one :favorite, through: :favorites will look for a
Only use it if the name cannot be inferred from the association.
Specifies the source association name used by #has_one :through queries.
[:source]
+has_one+ alone does not perform a join.
due to database limitations. This option is only applicable on has_one :through associations as
will be generated. Note that in some cases, if order or limit is applied, it will be done in-memory
Specifies whether joins should be skipped for an association. If set to true, two or more queries
[:disable_joins]
section above.)
the appropriate join model records when they are saved. (See the 'Association Join Models'
join model. This allows associated records to be built which will automatically create
a good idea to set the :inverse_of option on the source association on the
If you are going to modify the association (rather than just read from it), then it is
:through association directly.
as appropriate. Otherwise, the collection is read-only, so you should manipulate the
and the records on the :through model will be automatically created and removed
If the association on the join model is a #belongs_to, the collection can be modified
or #belongs_to association on the join model.
source reflection. You can only use a :through query through a #has_one
:primary_key, and :foreign_key are ignored, as the association uses the
Specifies a Join Model through which to perform the query. Options for :class_name,
[:through]
Specifies a polymorphic interface (See #belongs_to).
[:as]
Specify the method that returns the primary key used for the association. By default this is +id+.
[:primary_key]
default :foreign_type.
has_one :tag, as: :taggable association will use "taggable_type" as the
specified on "as" option with a "_type" suffix. So a class that defines a
association. By default this is guessed to be the name of the polymorphic association
Specify the column used to store the associated object's type, if this is a polymorphic
[:foreign_type]
a good idea to set the :inverse_of option.
If you are going to modify the association (rather than just read from it), then it is
will use "person_id" as the default :foreign_key.
of this class in lower-case and "_id" suffixed. So a Person class that makes a #has_one association
Specify the foreign key used for the association. By default this is guessed to be the name
[:foreign_key]
Note that :dependent option is ignored when using :through option.
* :restrict_with_error causes an error to be added to the owner if there is an associated object
* :restrict_with_exception causes an ActiveRecord::DeleteRestrictionError exception to be raised if there is an associated record
on polymorphic associations. Callbacks are not executed.
* :nullify causes the foreign key to be set to +NULL+. Polymorphic type column is also nullified
* :delete causes the associated object to be deleted directly from the database (so callbacks will not execute)
constraint actions will occur inside the same transaction that deletes its owner.
this option if the association is backed by foreign key constraints in your database. The foreign key
* :destroy_async causes the associated object to be destroyed in a background job. WARNING: Do not use
* :destroy causes the associated object to also be destroyed
* nil do nothing (default).
its owner is destroyed:
Controls what happens to the associated object when
[:dependent]
if the real class name is Person, you'll have to specify it with this option.
from the association name. So has_one :manager will by default be linked to the Manager class, but
Specify the class name of the association. Use it only if that name can't be inferred
[:class_name]
Options are:
The declaration can also include an +options+ hash to specialize the behavior of the association.
=== Options
has_one :latest_post, ->(blog) { where("created_at > ?", blog.enabled_at) }
has_one :employer, -> { joins(:company) }
has_one :author, -> { where(comment_id: 1) }
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
* Account#reload_beneficiary
* Account#create_beneficiary! (similar to b = Beneficiary.new(account_id: id); b.save!; b)
* Account#create_beneficiary (similar to b = Beneficiary.new(account_id: id); b.save; b)
* Account#build_beneficiary (similar to Beneficiary.new(account_id: id))
* Account#beneficiary=(beneficiary) (similar to beneficiary.account_id = account.id; beneficiary.save)
* Account#beneficiary (similar to Beneficiary.where(account_id: id).first)
An Account class declares has_one :beneficiary, which will add:
=== Example
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 = {})]
yet been saved.
with +attributes+ and linked to this object through a foreign key, but has not
Returns a new object of the associated type that has been instantiated
[build_association(attributes = {})]
associated object when assigning a new one, even if the new one isn't saved to database.
and saves the associate object. To avoid database inconsistencies, permanently deletes an existing
Assigns the associate object, extracts the primary key, sets it as the foreign key,
[association=(associate)]
Returns the associated object. +nil+ is returned if none is found.
[association]
has_one :manager would add among others manager.nil?.
+association+ is a placeholder for the symbol passed as the +name+ argument, so
The following methods for retrieval and query of a single associated object will be added:
on when to use #has_one and when to use #belongs_to.
then you should use #belongs_to instead. See also ActiveRecord::Associations::ClassMethods's overview
if the other class contains the foreign key. If the current class contains the foreign key,
Specifies a one-to-one association with another class. This method should only be used
def has_one(name, scope = nil, **options) reflection = Builder::HasOne.build(self, name, scope, options) Reflection.add_reflection self, name, reflection end