ActiveRecord belongs_to Association

Using belongs_to will create a one-to-one relationship from one ActiveRecord object to a single associated object for which it has a foreign key value.  Assigning an object to a belongs_to association will set the fk to the owner object, however the record will not be saved automatically in the database.  Calling belongs_to on a class establishes an attribute of the same name on instances of the class.  The attribute is really a proxy to the related ActiveRecord object.

Reloading the Association
Calling the accessor method with a parameter of true will force the association to be reloaded from the database.

Building and Creating Related Objects with the Association
belongs_to adds factory methods for creating new instances and connecting them with foreign keys automatically.
build_association does not save a new object, but create_association does.

belongs_to Options
:class_name # => specifies the name of the class for the association. Example:…

class Timesheet
belongs_to :user
belongs_to :approver, :class_name => ‘User’  # not an instance of Approver
end

:conditions # => Add conditions to a relationship that must be correct in order to be a valid relationship. Example..

# Note: conditions only affect how relationships are read from the database, not how they are created.

class Timesheet
belongs_to :approver, :class_name => ‘User’, :conditions = ['user.authorized_approver = ?', true]
end

:foreign_key # => Specifies the fk column used as opposed to the conventional <association>_id column.
belongs_to :administrator :foreign_key => ‘admin_user_id’

:counter_cache # => used to make Rails maintain a counter field automatically called <associations>_count
:counter_cache => true # use the default name for the counter field.
:counter_cache => ‘number_of_children’ # alternate name for the counter field (unconventional)
# be careful to initialize your counter cache column to 0 in the database

:include # => creates a left outer join to include associations in one query rather than N+1 queries.
# (I have talked about the :include parameter in the post about eager loading.)

:polymorphic => true
# The type of the related object is stored in the database along with its foreign key.
# When you make a :belongs_to association polymorphic, any other model in the system can fill the role. Example….

class Comment < ActiveRecord::Base
belongs_to :subject, :polymorphic => true
end

class ExpenseReport < ActiveRecord::Base
belongs_to :user
has_many :comments, :as => :subject
end

class Timesheet < ActiveRecord::Base
belongs_to :user
has_many :comments, :as => :subject
end

# In the database, the comments table would store a subject_type column to store the class name of the associated class.

~ by bandwagonblog on January 31, 2009.

Leave a Reply