UUID primary keys with ActiveRecord in Rails 3
Sometimes it is useful to have primary keys in ActiveRecord that are independent from a database’s autoincrement implementation. With ActiveSupport::Concern this can be done smoothly in Rails 3
Made a library? Written a blog post? Found a useful tutorial? Share it with the Ruby community here or just enjoy what everyone else has found!
Sometimes it is useful to have primary keys in ActiveRecord that are independent from a database’s autoincrement implementation. With ActiveSupport::Concern this can be done smoothly in Rails 3
Comments
I think it’s worth pointing out that you don’t really need ActiveSupport::Concern for this, it’s just API sugar for the
included
method inModule
. You can just as easily do:module Extensions module UUID def self.included(base) base.class_eval do set_primary_key 'uuid' before_create :generate_uuid
This is functionally the same. If you’re using Rails then using
ActiveSupport::Concern
is a nice shorthand, I just don’t want anybody to think that they need to install Active Support to do something like this outside of a Rails context.Is this something you can’t do with Rails 2?
If you decide to use an opinionated framework you should also adopt the possibilities and convention it offers. I think your code is antiquated when applied in a Rails 3 app as the “API sugar” you wrote about also handles module dependencies.
Improve wheels but don’t reinvent square wheels…
a nice solution
Not to rain on anyone’s parade, but it is worth noting that you can use UUIDs as primary-keys with DataMapper. You can even use DataMapper in a Rails 3 or 2 app with dm-rails.
be careful… mysql at least assumes your primary keys are integers and makes a lot of optimizations based on that. doing this could shred the performance of your database. i tried it once and regret it. i think they still haven’t migrated fully off of guids at grockit.
Post a comment