instance method
has_one
Ruby on Rails 6.0.6
Since v2.2.3Signature
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.
nilis 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
attributesand 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 toBeneficiary.where(account_id: id).first) -
Account#beneficiary=(beneficiary)(similar tobeneficiary.account_id = account.id; beneficiary.save) -
Account#build_beneficiary(similar toBeneficiary.new(account_id: id)) -
Account#create_beneficiary(similar tob = Beneficiary.new(account_id: id); b.save; b) -
Account#create_beneficiary!(similar tob = 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 :managerwill 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:
-
:destroycauses the associated object to also be destroyed -
:deletecauses the associated object to be deleted directly from the database (so callbacks will not execute) -
:nullifycauses the foreign key to be set toNULL. Polymorphic type column is also nullified on polymorphic associations. Callbacks are not executed. -
:restrict_with_exceptioncauses anActiveRecord::DeleteRestrictionErrorexception to be raised if there is an associated record -
:restrict_with_errorcauses an error to be added to the owner if there is an associated object
Note that
:dependentoption is ignored when using:throughoption. -
- :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_ofoption. - :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: :taggableassociation 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_keyare ignored, as the association uses the source reflection. You can only use a:throughquery 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_ofoption. - :source
-
Specifies the source association name used by #has_one
:throughqueries. Only use it if the name cannot be inferred from the association.has_one :favorite, through: :favoriteswill look for a:favoriteon Favorite, unless a:sourceis given. - :source_type
-
Specifies type of the source association used by #has_one
:throughqueries 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.falseby default. If you want to ensure associated objects are revalidated on every update, usevalidates_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
:autosavetotrue. - :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_ofto avoid an extra query during validation.
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
Parameters
-
namereq -
scopeopt = nil -
optionskeyrest
Source
# File activerecord/lib/active_record/associations.rb, line 1510
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 1510
· View on GitHub
· Improve this page
· Find usages on GitHub
Defined in ActiveRecord::Associations::ClassMethods