instance method
has_one
Ruby on Rails 2.2.3
Since v2.2.3Signature
has_one(association_id, 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(force_reload = false)
-
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.
- association.nil?
-
Returns
trueif there is no associated object. - 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. Note: This ONLY works if an association already exists. It will NOT work if the association isnil. - 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).
(association is replaced with the symbol passed as the first argument, so has_one :manager would add among others manager.nil?.)
Example
An Account class declares has_one :beneficiary, which will add:
-
Account#beneficiary(similar toBeneficiary.find(:first, :conditions => "account_id = #{id}")) -
Account#beneficiary=(beneficiary)(similar tobeneficiary.account_id = account.id; beneficiary.save) -
Account#beneficiary.nil? -
Account#build_beneficiary(similar toBeneficiary.new("account_id" => id)) -
Account#create_beneficiary(similar tob = Beneficiary.new("account_id" => id); b.save; b)
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. - :conditions
-
Specify the conditions that the associated object must meet in order to be included as a
WHERESQL fragment, such asrank = 5. - :order
-
Specify the order in which the associated objects are returned as an
ORDER BYSQL fragment, such aslast_name, first_name DESC. - :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. If set to:nullify, the associated object’s foreign key is set toNULL. Also, association is assigned. - :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_oneassociation will use “person_id” as the default:foreign_key. - :primary_key
-
Specify the method that returns the primary key used for the association. By default this is
id. - :include
-
Specify second-order associations that should be eager loaded when this object is loaded.
- :as
-
Specifies a polymorphic interface (See
belongs_to). - :select
-
By default, this is
*as inSELECT * FROM, but can be changed if, for example, you want to do a join but not include the joined columns. Do not forget to include the primary and foreign keys, otherwise it will raise an error. - :through
-
Specifies a Join Model through which to perform the query. Options for
:class_nameand:foreign_keyare ignored, as the association uses the source reflection. You can only use a:throughquery through ahas_oneorbelongs_toassociation on the join model. - :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 polymorphicbelongs_to. - :readonly
-
If true, the associated object is readonly through the association.
- :validate
-
If false, don’t validate the associated object when saving the parent object.
falseby default.
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, :class_name => "Comment", :order => "posted_on" has_one :project_manager, :class_name => "Person", :conditions => "role = 'project_manager'" has_one :attachment, :as => :attachable has_one :boss, :readonly => :true has_one :club, :through => :membership has_one :primary_address, :through => :addressables, :conditions => ["addressable.primary = ?", true], :source => :addressable
Parameters
-
association_idreq -
optionsopt = {}
Source
# File activerecord/lib/active_record/associations.rb, line 874
def has_one(association_id, options = {})
if options[:through]
reflection = create_has_one_through_reflection(association_id, options)
association_accessor_methods(reflection, ActiveRecord::Associations::HasOneThroughAssociation)
else
reflection = create_has_one_reflection(association_id, options)
ivar = "@#{reflection.name}"
method_name = "has_one_after_save_for_#{reflection.name}".to_sym
define_method(method_name) do
association = instance_variable_get(ivar) if instance_variable_defined?(ivar)
if !association.nil? && (new_record? || association.new_record? || association[reflection.primary_key_name] != id)
association[reflection.primary_key_name] = id
association.save(true)
end
end
after_save method_name
add_single_associated_validation_callbacks(reflection.name) if options[:validate] == true
association_accessor_methods(reflection, HasOneAssociation)
association_constructor_method(:build, reflection, HasOneAssociation)
association_constructor_method(:create, reflection, HasOneAssociation)
configure_dependency_for_has_one(reflection)
end
end
Defined in activerecord/lib/active_record/associations.rb line 874
· View on GitHub
· Improve this page
· Find usages on GitHub
Defined in ActiveRecord::Associations::ClassMethods