Forum: Ruby on Rails How do you make associations when a table has two unique columns?

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.
416a1ce25c1bf1e75f60e27d0221a903?d=identicon&s=25 blgroup (Guest)
on 2009-04-29 00:38
(Received via mailing list)
Having trouble with a somewhat unconventional modelling in Rails
2.2.2.

Take three table.

1. User model with primary integer id and a unique string guid.

2. Model X has foreign key to User as integer user_id and its model
includes
belongs_to :users

3. Model Y has foreign key to User as string user_guid and its model
includes
belongs_to :users, :foreign_key => 'user_guid'

This tells Rails which column to use in Model Y to look up Users.
But How do I tell Rails which column to use in User?

In other words, how do I tell Rails to join (or select) from
Users.guid instead of Users.id when  referencing Y.user?

The has_one and has_many association has a :primary_key option, but
this seems to be missing on the belongs_to association

How do people work around this?  Any help would be greatly
appreciated.

Thanks,
=Blair.
5772c599ccab3081e0fffb1d54f3b6de?d=identicon&s=25 Andrew Timberlake (andrewtimberlake)
on 2009-04-29 05:16
(Received via mailing list)
On Tue, Apr 28, 2009 at 9:38 PM, blgroup <blgroup@gmail.com> wrote:
> belongs_to :users
>
> 3. Model Y has foreign key to User as string user_guid and its model
> includes
> belongs_to :users, :foreign_key => 'user_guid'

Are you sure you don't mean:
belongs_to :user, :foreign_key => 'user_guid' #<- Using singular 'user'
then Y.user should work fine

>
> How do people work around this?  Any help would be greatly
> appreciated.
>
> Thanks,
> =Blair.

Setup your user model like this:

class User < ActiveRecord::Base
  set_primary_key :guid
end


Andrew Timberlake
http://ramblingsonrails.com
http://www.linkedin.com/in/andrewtimberlake

"I have never let my schooling interfere with my education" - Mark Twain
This topic is locked and can not be replied to.