Skip to content

Instantly share code, notes, and snippets.

@lfittl
Last active September 8, 2016 00:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lfittl/12aded0ff526981e890b50861dc129e4 to your computer and use it in GitHub Desktop.
Save lfittl/12aded0ff526981e890b50861dc129e4 to your computer and use it in GitHub Desktop.
# Place this in app/models/concerns/fix_composite_key_insert.rb
# Fix for https://github.com/composite-primary-keys/composite_primary_keys/issues/365
#
# Act as if the record has a single primary key column in some cases, in
# particular when we get called from _create_record with the RETURNING result:
# https://github.com/rails/rails/blob/master/activerecord/lib/active_record/persistence.rb#L560
module FixCompositeKeyInsert
extend ActiveSupport::Concern
included do
def id
if self.class.primary_key.is_a?(Array)
return unless attributes[self.class.primary_key[0]].present?
end
super
end
def id=(value)
if self.class.primary_key.is_a?(Array) && !value.is_a?(Array)
return super([value] + self.class.primary_key[1..-1].map { |a| attributes[a] })
end
super(value)
end
end
end
class YourModel < ActiveRecord::Base
include FixCompositeKeyInsert
# ...
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment