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

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.

reset_association

Unloads the associated object. The next access will query it from the database.

Example

class Account < ActiveRecord::Base
  has_one :beneficiary
end

Declaring has_one :beneficiary adds the following methods (and more):

account = Account.find(5)
beneficiary = Beneficiary.find(8)

account.beneficiary               # similar to Beneficiary.find_by(account_id: 5)
account.beneficiary = beneficiary # similar to beneficiary.update(account_id: 5)
account.build_beneficiary         # similar to Beneficiary.new(account_id: 5)
account.create_beneficiary        # similar to Beneficiary.create(account_id: 5)
account.create_beneficiary!       # similar to Beneficiary.create!(account_id: 5)
account.reload_beneficiary
account.reset_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.

Setting the :foreign_key option prevents automatic detection of the association’s inverse, so it is generally a good idea to set the :inverse_of option as well.

: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 the association on the join model is a #belongs_to, the collection can be modified and the records on the :through model will be automatically created and removed as appropriate. Otherwise, the collection is read-only, so you should manipulate the :through association directly.

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 on the source association on the join model. This allows associated records to be built which will automatically create the appropriate join model records when they are saved. (See the ‘Association Join Models’ and ‘Setting Inverses’ sections above.)

:disable_joins

Specifies whether joins should be skipped for an association. If set to true, two or more queries will be generated. Note that in some cases, if order or limit is applied, it will be done in-memory due to database limitations. This option is only applicable on has_one :through associations as has_one alone does not perform a join.

: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.

:touch

If true, the associated object will be touched (the updated_at / updated_on attributes set to current time) 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 / updated_on attribute. Please note that no validation will be performed when touching, and only the after_touch, after_commit, and after_rollback callbacks will be executed.

: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.

:query_constraints

Serves as a composite foreign key. Defines the list of columns to be used to query the associated object. This is an optional option. By default Rails will attempt to derive the value automatically. When the value is set the Array size must match associated model’s primary key or query_constraints size.

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 :club, through: :membership, disable_joins: true
has_one :primary_address, -> { where(primary: true) }, through: :addressables, source: :addressable
has_one :credit_card, required: true
has_one :credit_card, strict_loading: true
has_one :employment_record_book, query_constraints: [:organization_id, :employee_id]
Show source
Register or log in to add new notes.
August 25, 2010 - (>= v2.3.8)
3 thanks

Undocumented :inverse_of option

Support for the :inverse_of option was backported to 2.3.6+.

Here’s the description from the original commit: http://github.com/rails/rails/commit/ccea98389abbf150b886c9f964b1def47f00f237


You can now add an :inverse_of option to has_one, has_many and belongs_to associations. This is best described with an example:

class Man < ActiveRecord::Base
  has_one :face, :inverse_of => :man
end

class Face < ActiveRecord::Base
  belongs_to :man, :inverse_of => :face
end

m = Man.first
f = m.face

Without :inverse_of m and f.man would be different instances of the same object (f.man being pulled from the database again). With these new :inverse_of options m and f.man are the same in memory instance.

Currently :inverse_of supports has_one and has_many (but not the :through variants) associations. It also supplies inverse support for belongs_to associations where the inverse is a has_one and it’s not a polymorphic.

September 25, 2008
2 thanks

Support for the option through

class Magazine < ActiveRecord::Base

  has_many :subscriptions
end

class Subscription < ActiveRecord::Base
  belongs_to :magazine
  belongs_to :user
end

class User < ActiveRecord::Base
  has_many :subscriptions
  has_one :magazine, :through => :subscriptions, :conditions => ['subscriptions.active = ?', true]
end
October 14, 2009
2 thanks

build_association deletes existing dependent record

Surprisingly (at least I was surprised), when an associated record exists, the build_association method immediately NULLs the foreign key in the database.

So if you write a singleton “new” action for the association in the obvious way (calling build_association), then just visiting the page will disconnect an existing associated record. This violates the principle that a GET request shouldn’t affect the database.

To avoid this, you can check for an existing association first, and redirect to the show action.

April 27, 2009
0 thanks

has_one through belongs_to not working

code example:

class Company < ActiveRecord::Base
  has_many :route_lists
end

class RouteList < ActiveRecord::Base
  belongs_to :company
  has_many :routes
end

class Route < ActiveRecord::Base
  belongs_to :route_list
  has_one :company :through => :route_list
end

This creates an invalid SQL query, where the keys in the join between route and routelist are switched, when used as an include:

Routes.find :all, :conditions => ["companies.type = ?", "Account"], :include => :company

route_lists.route_list_id = route.id

instead of: route_lists.id = route.route_list_id