Composite Primary Keys for gem developers

I look after three gems that use primary keys in their codebase. I’ve had PR’s from people wanting to add composite primary key support into these. We’ve added it to ActsAsList but I’m wondering if there’s a more transparent way to support composite keys where the gem developer doesn’t have to determine:

  • Does this Rails version even support composite keys?
  • Is a composite primary key in use on this particular model?

I’ve had a fairly good look through the code and docs but couldn’t quite figure out if there was a way to blindly refer to a primary key without needing to know if it’s composite or not.

1 Like

I’ve found some allusion to the problem here: Fix counter caches to work for models with composite primary keys by fatkodima · Pull Request #50983 · rails/rails · GitHub

The main learning was if you want a scope on the primary key whether or not it is a composite primary key, you can do so in with the form:

parent.children.where(Child.primary_key => [some_child.id])
1 Like