belongs_to_association.rb 2.0 KB
Newer Older
1 2 3
module ActiveRecord
  module Associations
    class BelongsToAssociation < AssociationProxy #:nodoc:
4 5 6 7 8
      def initialize(owner, association_name, association_class_name, association_class_primary_key_name, options)
        super        
        construct_sql        
      end
      
9 10 11 12 13 14
      def reset
        @target = nil
        @loaded = false
      end

      def create(attributes = {})
15 16
        record = @association_class.create(attributes)
        replace(record, true)
17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
        record
      end

      def build(attributes = {})
        record = @association_class.new(attributes)
        replace(record, true)
        record
      end

      def replace(obj, dont_save = false)
        if obj.nil?
          @target = @owner[@association_class_primary_key_name] = nil
        else
          raise_on_type_mismatch(obj) unless obj.nil?

32
          @target = (AssociationProxy === obj ? obj.target : obj)
33
          @owner[@association_class_primary_key_name] = obj.id unless obj.new_record?
34
          @updated = true
35 36 37
        end
        @loaded = true

38
        return (@target.nil? ? nil : self)
39
      end
40
      
41 42 43 44
      def updated?
        @updated
      end
      
45 46 47
      private
        def find_target
          if @options[:conditions]
48 49 50 51 52
            @association_class.find(
              @owner[@association_class_primary_key_name], 
              :conditions => interpolate_sql(@options[:conditions]),
              :include    => @options[:include]
            )
53
          else
54
            @association_class.find(@owner[@association_class_primary_key_name], :include => @options[:include])
55 56 57
          end
        end

58 59 60 61
        def foreign_key_present
          !@owner[@association_class_primary_key_name].nil?
        end

62 63 64
        def target_obsolete?
          @owner[@association_class_primary_key_name] != @target.id
        end
65
        
66
        def construct_sql
67
          @finder_sql = "#{@association_class.table_name}.#{@association_class.primary_key} = #{@owner.id}"
68 69 70 71
        end
    end
  end
end