# Legacy database, primary key compound with two fields

**URL:** <https://www.ruby-forum.com/t/legacy-database-primary-key-compound-with-two-fields/173028>\
**Category:** Rails\
**Created:** [July 31, 2009, 5:54pm UTC](https://www.ruby-forum.com/t/legacy-database-primary-key-compound-with-two-fields/173028 "2009-07-31T17:54:55Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![craigrails](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/c/c2a13f/32.png) [@craigrails](https://www.ruby-forum.com/u/craigrails)\
**Post date:** [July 31, 2009, 5:54pm UTC](https://www.ruby-forum.com/t/legacy-database-primary-key-compound-with-two-fields/173028/1 "2009-07-31T17:54:55Z")

</div>

I am trying to define a model for a legacy database and the primary key  
is the combination of two fields, ‘branchcode’ and ‘debtorno’

class Custbranch \< ActiveRecord::Base

set\_table\_name ‘custbranch’  
set\_primary\_key ‘branchcode\_branchno’

end

and I have tried…

set\_primary\_key ‘branchcode branchno’  
set\_primary\_key ‘branchcode, branchno’

but in the console, a simple find, always an error…

> > @branch=Custbranch.find(“A365”)  
> > ActiveRecord::StatementInvalid: Mysql::Error: Unknown column  
> > ‘custbranch.branchcode\_branchno’ in ‘where clause’: SELECT \* FROM  
> > `custbranch` WHERE (`custbranch`.`branchcode_branchno` = ‘A365’)

> > @branch = Custbranch.find(“A365”)  
> > ActiveRecord::StatementInvalid: Mysql::Error: Unknown column  
> > ‘custbranch.branchcode branchno’ in ‘where clause’: SELECT \* FROM  
> > `custbranch` WHERE (`custbranch`.`branchcode branchno` = ‘A365’)

> > @branch = Custbranch.find(“A365”)  
> > ActiveRecord::StatementInvalid: Mysql::Error: Unknown column  
> > ‘custbranch.branchcode, branchno’ in ‘where clause’: SELECT \* FROM  
> > `custbranch` WHERE (`custbranch`.`branchcode, branchno` = ‘A365’)

and the only way I seem to make it work is to use ‘branchcode’ as the  
primary key which is not indexed. I can use this for now but I am  
wondering if it is possible to set\_primary\_key on a legacy db model to  
use a compound index/primary key.

Craig

–  
This message has been scanned for viruses and  
dangerous content by MailScanner, and is  
believed to be clean.

---

<div class="post-metadata">

**Author:** ![craigrails](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/c/c2a13f/32.png) [@craigrails](https://www.ruby-forum.com/u/craigrails)\
**Post date:** [July 31, 2009, 6:50pm UTC](https://www.ruby-forum.com/t/legacy-database-primary-key-compound-with-two-fields/173028/2 "2009-07-31T18:50:29Z")

</div>

Craig W. wrote:

> I am trying to define a model for a legacy database and the primary key  
> is the combination of two fields, ‘branchcode’ and ‘debtorno’  
> […]

If you can’t add a surrogate key, try the composite\_primary\_keys plugin.

## Best,

Marnen Laibow-Koser  
[http://www.marnen.org](http://www.marnen.org)  
removed\_email\_address@domain.invalid
