Last active
September 8, 2016 00:34
-
-
Save lfittl/12aded0ff526981e890b50861dc129e4 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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