instance method belongs_to

Ruby on Rails 2.2.3

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

belongs_to(association_id, options = {})

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

Methods will be added for retrieval and query for a single associated object, for which this object holds an id:

association(force_reload = false)

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

association=(associate)

Assigns the associate object, extracts the primary key, and sets it as the foreign key.

association.nil?

Returns true if there is no associated object.

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

(association is replaced with the symbol passed as the first argument, so belongs_to :author would add among others author.nil?.)

Example

A Post class declares belongs_to :author, which will add:

  • Post#author (similar to Author.find(author_id))

  • Post#author=(author) (similar to post.author_id = author.id)

  • Post#author? (similar to post.author == some_author)

  • Post#author.nil?

  • Post#build_author (similar to post.author = Author.new)

  • Post#create_author (similar to post.author = Author.new; post.author.save; post.author)

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

Options

: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 :author will by default be linked to the Author 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 WHERE SQL fragment, such as authorized = 1.

:select

By default, this is * as in SELECT * 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.

:foreign_key

Specify the foreign key used for the association. By default this is guessed to be the name of the association with an “_id” suffix. So a class that defines a belongs_to :person association will use “person_id” as the default :foreign_key. Similarly, belongs_to :favorite_person, :class_name => "Person" will use a foreign key of “favorite_person_id”.

: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. This option should not be specified when belongs_to is used in conjunction with a has_many relationship on another class because of the potential to leave orphaned records behind.

:counter_cache

Caches the number of belonging objects on the associate class through the use of increment_counter and decrement_counter. The counter cache is incremented when an object of this class is created and decremented when it’s destroyed. This requires that a column named #{table_name}_count (such as comments_count for a belonging Comment class) is used on the associate class (such as a Post class). You can also specify a custom counter cache column by providing a column name instead of a true/false value to this option (e.g., :counter_cache => :my_custom_counter.) Note: Specifying a counter cache will add it to that model’s list of readonly attributes using attr_readonly.

:include

Specify second-order associations that should be eager loaded when this object is loaded.

:polymorphic

Specify this association is a polymorphic association by passing true. Note: If you’ve enabled the counter cache, then you may want to add the counter cache attribute to the attr_readonly list in the associated classes (e.g. class Post; attr_readonly :comments_count; end).

:readonly

If true, the associated object is readonly through the association.

:validate

If false, don’t validate the associated objects when saving the parent object. false by default.

Option examples:

belongs_to :firm, :foreign_key => "client_of"
belongs_to :author, :class_name => "Person", :foreign_key => "author_id"
belongs_to :valid_coupon, :class_name => "Coupon", :foreign_key => "coupon_id",
           :conditions => 'discounts > #{payments_count}'
belongs_to :attachable, :polymorphic => true
belongs_to :project, :readonly => true
belongs_to :post, :counter_cache => true

Parameters

association_id req
options opt = {}
Source
# File activerecord/lib/active_record/associations.rb, line 987
      def belongs_to(association_id, options = {})
        reflection = create_belongs_to_reflection(association_id, options)

        ivar = "@#{reflection.name}"

        if reflection.options[:polymorphic]
          association_accessor_methods(reflection, BelongsToPolymorphicAssociation)

          method_name = "polymorphic_belongs_to_before_save_for_#{reflection.name}".to_sym
          define_method(method_name) do
            association = instance_variable_get(ivar) if instance_variable_defined?(ivar)

            if association && association.target
              if association.new_record?
                association.save(true)
              end

              if association.updated?
                self[reflection.primary_key_name] = association.id
                self[reflection.options[:foreign_type]] = association.class.base_class.name.to_s
              end
            end
          end
          before_save method_name
        else
          association_accessor_methods(reflection, BelongsToAssociation)
          association_constructor_method(:build,  reflection, BelongsToAssociation)
          association_constructor_method(:create, reflection, BelongsToAssociation)

          method_name = "belongs_to_before_save_for_#{reflection.name}".to_sym
          define_method(method_name) do
            association = instance_variable_get(ivar) if instance_variable_defined?(ivar)

            if !association.nil?
              if association.new_record?
                association.save(true)
              end

              if association.updated?
                self[reflection.primary_key_name] = association.id
              end
            end
          end
          before_save method_name
        end

        # Create the callbacks to update counter cache
        if options[:counter_cache]
          cache_column = options[:counter_cache] == true ?
            "#{self.to_s.demodulize.underscore.pluralize}_count" :
            options[:counter_cache]

          method_name = "belongs_to_counter_cache_after_create_for_#{reflection.name}".to_sym
          define_method(method_name) do
            association = send(reflection.name)
            association.class.increment_counter(cache_column, send(reflection.primary_key_name)) unless association.nil?
          end
          after_create method_name

          method_name = "belongs_to_counter_cache_before_destroy_for_#{reflection.name}".to_sym
          define_method(method_name) do
            association = send(reflection.name)
            association.class.decrement_counter(cache_column, send(reflection.primary_key_name)) unless association.nil?
          end
          before_destroy method_name

          module_eval(
            "#{reflection.class_name}.send(:attr_readonly,\"#{cache_column}\".intern) if defined?(#{reflection.class_name}) && #{reflection.class_name}.respond_to?(:attr_readonly)"
          )
        end

        add_single_associated_validation_callbacks(reflection.name) if options[:validate] == true

        configure_dependency_for_belongs_to(reflection)
      end

Defined in activerecord/lib/active_record/associations.rb line 987 · 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