Forum: Ruby on Rails Anyone find workaround for composite primary keys in AR?

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
rodney.clang (Guest)
on 2005-12-02 23:34
(Received via mailing list)
These old legacy tables are going to get the best of me yet. I have 3
fields comprising the primary key in some instances. Unfortunately can't
add an ID auto increment field.

I was wondering if anyone did anything tricky with views, replication or
fancy Ruby code to adress this big legacy data need ?
-r
grzm (Guest)
on 2005-12-07 04:24
(Received via mailing list)
On Dec 3, 2005, at 6:32 , Rodney Clang wrote:

> These old legacy tables are going to get the best of me yet. I have
> 3 fields comprising the primary key in some instances.
> Unfortunately can't add an ID auto increment field.
>
> I was wondering if anyone did anything tricky with views,
> replication or fancy Ruby code to adress this big legacy data need ?

I'm sorry, I haven't been following this thread, but had an idea that
might be workable if you're using PostgreSQL (or another dbms that
supports views and rules).

Create a table with four columns, one of which is serial and will be
your Rails-friendly pkey, e.g.,

create table pk_join_table (
	id serial primary key
	, compound_pkey_part1 footype not null
	, compound_pkey_part2 bartype not null
	, compound_pkey_part3 baztype not null
	, unique (compound_pkey_part1,compound_pkey_part2,compound_pkey_part3)
	, foreign key
(compound_pkey_part1,compound_pkey_part2,compound_pkey_part3)
		references legacy_table ( compound_pkey_part1, compound_pkey_part2
			, compound_pkey_part3)
);

Then create a view:

create view new_rails_friendly_table as
select *
from pk_join_table
join legacy_table using (compound_pkey_part1, compound_pkey_part2
	, compound_pkey_part3)
;

Then you could create the appropriate insert, update, and delete
rules in PostgreSQL to make sure things get properly placed. Map
ActiveRecord to the view, not the pk_join_table or legacy_table. (I
believe it's possible, but I don't have much experience writing rules.)

I'm not sure how Rails will handle pkey generation though. The folks
putting together the UUID (or is it GUID?) work for Rails might know
how to get around that.

Hope this helps a bit.

Michael G.
grzm myrealbox com
This topic is locked and can not be replied to.