Categories
Rails

Rails composite primary key support

I am working with a legacy database. Usually, the built in rails stuff for table prefixing and primary key changes is enough. Sometimes, it’s not.

I had a problem with a join table that has Foreign Key names that are tablename_id, but the tables they reference is tablename_id as well. The has_and_belongs_to_many method DID NOT like it at all. Added to this is that there are attributes in the join table (is_primary) that I need to use. I considered (and discussed with the Java devs) the option of making the join table have an ID and making it a model, but there was potential for breakage and I like to tred very carefully around the existing app and making changes.

So, a bit of time on Google later, and I came across Nic Williams’ Composite Primary Key plugin. Oh man, it works a treat. I created the model for the join table, specified the primary keys, and went as normal!

Beautiful.