Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Default primary key value is incompatible with accepts_nested_attributes_for #66

Open
ivanoblomov opened this issue Jun 1, 2015 · 1 comment

Comments

@ivanoblomov
Copy link
Contributor

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
Copy link
Contributor Author

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 ivanoblomov changed the title Default primary key value causes incompatibilities with accepts_nested_attributes_for Default primary key value is incompatible with accepts_nested_attributes_for Jun 2, 2015
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant