Skip to content

Natural Primary Key Supported? #19

metaskills opened this Issue Feb 28, 2010 · 1 comment

1 participant


I'm almost about to find this out myself. Legacy database with a model that has non integer primary keys. Simple strings like "AA-12345" and right now they are not saving due to:

# Validate format of ancestry column value
validates_format_of ancestry_column, :with => /\A[0-9]+(\/[0-9]+)*\Z/, :allow_nil => true

I'm gonna rewrite that to allow natural primary keys, but wanted to know if this topic has come up before?


So here are my results, ancestry does work with natural primary keys as long as you do the following. First, you change the validation to this below. This just allows everything in the key other than the "/" delimiter.

validates_format_of :ancestry, :with => %r|\A[^/]+(\/[^/]+)*\Z|, :allow_nil => true

Then change the #ancestor_ids method to not map each value #to_i. This is not really needed anyway since AR find can take IDs in a string or a integers. However, I never really ran the tests after making this change which if the #ancestor_ids were used in a "IN (?)" conditions might be a problem. So what I did was apply this patch in my model that has_ancestry which used natural keys. Perhaps this behavior could be an "options" or you could better yet, reflect on the schema too and just do it automatically. I could come up with a tested patch if interested.

def ancestor_ids

This issue was closed.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.