primary_key.rb 2.4 KB
Newer Older
1 2 3 4 5
module ActiveRecord
  module AttributeMethods
    module PrimaryKey
      extend ActiveSupport::Concern

6 7
      # Returns this record's primary key value wrapped in an Array or nil if
      # the record is not persisted? or has just been destroyed.
8
      def to_key
9 10
        key = send(self.class.primary_key)
        [key] if key
11 12
      end

13 14 15 16
      module ClassMethods
        # Defines the primary key field -- can be overridden in subclasses. Overwriting will negate any effect of the
        # primary_key_prefix_type setting, though.
        def primary_key
17
          @primary_key ||= reset_primary_key
18 19
        end

20 21 22 23 24
        # Returns a quoted version of the primary key name, used to construct SQL statements.
        def quoted_primary_key
          @quoted_primary_key ||= connection.quote_column_name(primary_key)
        end

25
        def reset_primary_key #:nodoc:
26 27 28
          key = self == base_class ? get_primary_key(base_class.name) :
            base_class.primary_key

29 30 31 32 33
          set_primary_key(key)
          key
        end

        def get_primary_key(base_name) #:nodoc:
34
          return 'id' unless base_name && !base_name.blank?
35

36
          case primary_key_prefix_type
A
Aaron Patterson 已提交
37
          when :table_name
38
            base_name.foreign_key(false)
A
Aaron Patterson 已提交
39
          when :table_name_with_underscore
40
            base_name.foreign_key
A
Aaron Patterson 已提交
41
          else
42 43 44 45 46
            if ActiveRecord::Base != self && connection.table_exists?(table_name)
              connection.primary_key(table_name)
            else
              'id'
            end
47 48 49
          end
        end

50
        attr_accessor :original_primary_key
51 52 53 54 55 56
        
        # Attribute writer for the primary key column
        def primary_key=(value)
          @quoted_primary_key = nil
          @primary_key = value
        end
57

58 59 60 61 62 63 64 65
        # Sets the name of the primary key column to use to the given value,
        # or (if the value is nil or false) to the value returned by the given
        # block.
        #
        #   class Project < ActiveRecord::Base
        #     set_primary_key "sysid"
        #   end
        def set_primary_key(value = nil, &block)
66
          @quoted_primary_key = nil
67 68 69
          @primary_key ||= ''
          self.original_primary_key = @primary_key
          value &&= value.to_s
70
          connection_pool.primary_keys[table_name] = value
71
          self.primary_key = block_given? ? instance_eval(&block) : value
72 73 74 75 76
        end
      end
    end
  end
end