instance method has_one

Ruby on Rails 6.1.7.10

Since v2.2.3

Available in: v2.2.3 v2.3.18 v3.0.20 v3.1.12 v3.2.22.5 v4.0.13 v4.1.16 v4.2.9 v5.2.8.1 v6.0.6 v6.1.7.10 v7.0.10 v7.1.6 v7.2.3 v8.0.4 v8.1.2

Signature

has_one(name, scope = nil, **options)

Specifies a one-to-one association with another class. This method should only be used if the other class contains the foreign key. If the current class contains the foreign key, then you should use #belongs_to instead. See also ActiveRecord::Associations::ClassMethods’s overview on when to use #has_one and when to use #belongs_to.

The following methods for retrieval and query of a single associated object will be added:

association is a placeholder for the symbol passed as the name argument, so has_one :manager would add among others manager.nil?.

association

Returns the associated object. nil is returned if none is found.

association=(associate)

Assigns the associate object, extracts the primary key, sets it as the foreign key, and saves the associate object. To avoid database inconsistencies, permanently deletes an existing associated object when assigning a new one, even if the new one isn’t saved to database.

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 raises ActiveRecord::RecordInvalid if the record is invalid.

reload_association

Returns the associated object, forcing a database read.

Example

An Account class declares has_one :beneficiary, which will add:

  • Account#beneficiary (similar to Beneficiary.where(account_id: id).first)

  • Account#beneficiary=(beneficiary) (similar to beneficiary.account_id = account.id; beneficiary.save)

  • Account#build_beneficiary (similar to Beneficiary.new(account_id: id))

  • 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#reload_beneficiary

Scopes

You can pass a second argument scope as a callable (i.e. proc or lambda) to retrieve a specific record or customize the generated query when you access the associated object.

Scope examples:

has_one :author, -> { where(comment_id: 1) }
has_one :employer, -> { joins(:company) }
has_one :latest_post, ->(blog) { where("created_at > ?", blog.enabled_at) }

Options

The declaration can also include an options hash to specialize the behavior of the association.

Options are:

:class_name

Specify the class name of the association. Use it only if that name can’t be inferred from the association name. So has_one :manager will by default be linked to the Manager class, but if the real class name is Person, you’ll have to specify it with this option.

:dependent

Controls what happens to the associated object when its owner is destroyed:

  • nil do nothing (default).

  • :destroy causes the associated object to also be destroyed

  • :destroy_async causes the associated object to be destroyed in a background job. WARNING: Do not use this option if the association is backed by foreign key constraints in your database. The foreign key constraint actions will occur inside the same transaction that deletes its owner.

  • :delete causes the associated object to be deleted directly from the database (so callbacks will not execute)

  • :nullify causes the foreign key to be set to NULL. Polymorphic type column is also nullified on polymorphic associations. Callbacks are not executed.

  • :restrict_with_exception causes an ActiveRecord::DeleteRestrictionError exception to be raised if there is an associated record

  • :restrict_with_error causes an error to be added to the owner if there is an associated object

Note that :dependent option is ignored when using :through option.

:foreign_key

Specify the foreign key used for the association. By default this is guessed to be the name of this class in lower-case and “_id” suffixed. So a Person class that makes a #has_one association will use “person_id” as the default :foreign_key.

If you are going to modify the association (rather than just read from it), then it is a good idea to set the :inverse_of option.

: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 polymorphic association specified on “as” option with a “_type” suffix. So a class that defines a has_one :tag, as: :taggable association will use “taggable_type” as the default :foreign_type.

:primary_key

Specify the method that returns the primary key used for the association. By default this is id.

:as

Specifies a polymorphic interface (See #belongs_to).

:through

Specifies a Join Model through which to perform the query. Options for :class_name, :primary_key, and :foreign_key are ignored, as the association uses the source reflection. You can only use a :through query through a #has_one or #belongs_to association on the join model.

If you are going to modify the association (rather than just read from it), then it is a good idea to set the :inverse_of option.

:source

Specifies the source association name used by #has_one :through queries. Only use it if the name cannot be inferred from the association. has_one :favorite, through: :favorites will look for a :favorite on Favorite, unless a :source is given.

:source_type

Specifies type of the source association used by #has_one :through queries where the source association is a polymorphic #belongs_to.

:validate

When set to true, validates new objects added to association when saving the parent object. false by default. If you want to ensure associated objects are revalidated on every update, use validates_associated.

: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 NestedAttributes::ClassMethods#accepts_nested_attributes_for sets :autosave to true.

:inverse_of

Specifies the name of the #belongs_to association on the associated object that is the inverse of this #has_one association. See ActiveRecord::Associations::ClassMethods’s overview on Bi-directional associations for more detail.

:required

When set to true, the association will also have its presence validated. This will validate the association itself, not the id. You can use :inverse_of to avoid an extra query during validation.

:strict_loading

Enforces strict loading every time the associated record is loaded through this association.

:ensuring_owner_was

Specifies an instance method to be called on the owner. The method must return true in order for the associated records to be deleted in a background job.

Option examples:

has_one :credit_card, dependent: :destroy  # destroys the associated credit card
has_one :credit_card, dependent: :nullify  # updates the associated records foreign
                                              # key value to NULL rather than destroying it
has_one :last_comment, -> { order('posted_on') }, class_name: "Comment"
has_one :project_manager, -> { where(role: 'project_manager') }, class_name: "Person"
has_one :attachment, as: :attachable
has_one :boss, -> { readonly }
has_one :club, through: :membership
has_one :primary_address, -> { where(primary: true) }, through: :addressables, source: :addressable
has_one :credit_card, required: true
has_one :credit_card, strict_loading: true

Parameters

name req
scope opt = nil
options keyrest
Source
# File activerecord/lib/active_record/associations.rb, line 1607
        def has_one(name, scope = nil, **options)
          reflection = Builder::HasOne.build(self, name, scope, options)
          Reflection.add_reflection self, name, reflection
        end

Defined in activerecord/lib/active_record/associations.rb line 1607 · View on GitHub · Improve this page · Find usages on GitHub

Defined in ActiveRecord::Associations::ClassMethods

Type at least 2 characters to search.

↑↓ navigate · open · esc close