LoginSignup
3

More than 5 years have passed since last update.

composite_primary_keysを使用するとidが使えなくなるっぽい

Last updated at Posted at 2015-07-09

composite_primary_keysのgemを入れると、saveした時にidにnilが入るので、元の挙動(auto incrementの値が代入される)となるようにするパッチ。

Gem

rails (ver. 4.2.0)
composite_primary_keys (ver. 8.1.0)

Code

以下のソースを/config/initializers以下に配置する。

composite_primary_keys_patch.rb
module ActiveRecord
  module Persistence

    def _create_record(attribute_names = self.attribute_names)
      attributes_values = arel_attributes_with_values_for_create(attribute_names)

      new_id = self.class.unscoped.insert attributes_values

      if self.class.primary_key.kind_of?(Array)
        if self.class.primary_key.include?('id')
          primary_keys = {}
          attributes_values.each { |key, value|
            if self.class.primary_key.include?(key.name)
              primary_keys[key.name] = value
            end
          }
          new_ids = []
          self.class.primary_key.map { |key|
            if key == 'id'
              new_ids << new_id
            else
              new_ids << primary_keys[key]
            end
          }
          self.id = new_ids
        else
          self.id ||= new_id if self.class.primary_key
        end
      else
        self.id ||= new_id if self.class.primary_key
      end

      @new_record = false
      id
    end

  end

  module AttributeMethods
    module Read
      def read_attribute(attr_name, &block)
        # CPK
        if attr_name.kind_of?(Array)
          _read_attribute(attr_name, &block)
        else
          name = attr_name.to_s
          _read_attribute(name, &block)
        end
      end
    end
  end

end

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
What you can do with signing up
3