activeuuid icon indicating copy to clipboard operation
activeuuid copied to clipboard

Default primary key value is incompatible with accepts_nested_attributes_for

Open ivanoblomov opened this issue 10 years ago • 1 comments
trafficstars

Activeuuid defaults the primary key of new records to a UUID with a value of "00000000-0000-0000-0000-000000000000" whereas ActiveRecord expects all keys of new records to be nil.

This breaks accepts_nested_attributes_for because, seeing the non-nil UUID, ActiveRecord tries to find the non-existent record (with "00000000-0000-0000-0000-000000000000" as an ID).

ivanoblomov avatar Jun 01 '15 17:06 ivanoblomov

Here's a hacky work-around (since we couldn't work out where the UUID assignment was happening in the library's metaprogrammed magic).

In lib/ext/active_record.rb:

# For details on extending ActiveRecord see:
# http://stackoverflow.com/questions/2328984/rails-extending-activerecordbase
module ActiveRecordExtension
  extend ActiveSupport::Concern

  included do
    include ActiveUUID::UUID
    after_initialize :delete_zeroed_uuid
    before_create :set_id
  end

  private

  def delete_zeroed_uuid
    self.id = nil if zeroed_uuid?
  end

  def set_id
    return unless zeroed_uuid?
    self.id = SecureRandom.uuid
  end

  def zeroed_uuid?
    id.to_s == '00000000000000000000000000000000' ||
      id.to_s == '00000000-0000-0000-0000-000000000000'
  end
end

# include the extension
ActiveRecord::Base.send(:include, ActiveRecordExtension) unless
  File.basename($PROGRAM_NAME) == 'rake' && ARGV.include?('db:migrate')

ivanoblomov avatar Jun 02 '15 18:06 ivanoblomov