# Has\_one not using the pk?

**URL:** <https://www.ruby-forum.com/t/has-one-not-using-the-pk/57138>\
**Category:** Rails\
**Created:** [April 7, 2006, 2:11pm UTC](https://www.ruby-forum.com/t/has-one-not-using-the-pk/57138 "2006-04-07T14:11:05Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![ddirk](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/d/a9adbd/32.png) [@ddirk](https://www.ruby-forum.com/u/ddirk)\
**Post date:** [April 7, 2006, 2:11pm UTC](https://www.ruby-forum.com/t/has-one-not-using-the-pk/57138/1 "2006-04-07T14:11:05Z")

</div>

Hello,

im trying to wrap a fairly ugly legacy schema using AR. How to handle  
normalized informations which aren’t connected via the pk?

create table what (  
myid int,  
myclass int, ;; references blahclass.blahid  
mygender int  
)

create table blahclass (  
blahid int,  
mdesc1 text,  
fdesc1 text)  
)

I would like to wrap this as

class What \< AR::Base  
has\_one :blahclass

class Blahclass \< AR::Base  
belongs\_to :who

The problem is that a lookup of who.blahclass uses the who.pk to get the  
Blahclass record, but it should use who.blahclass. I dont find a way to  
specify this.

Of course it would be easy to hardwire the logic into a method, but i  
would like to use the normal relation wiring …

Cheers,  
Dirk

---

<div class="post-metadata">

**Author:** ![ddirk](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/d/a9adbd/32.png) [@ddirk](https://www.ruby-forum.com/u/ddirk)\
**Post date:** [April 7, 2006, 2:27pm UTC](https://www.ruby-forum.com/t/has-one-not-using-the-pk/57138/2 "2006-04-07T14:27:49Z")

</div>

On Apr 7, 2006, at 8:11 AM, Dirk Vleugels wrote:

> would like to use the normal relation wiring …
> 
> Cheers,  
> Dirk

First off, your has\_one and belongs\_to are backwards. Beyond that  
you just need to specify the foreign key field:

class What \< AR::Base  
belongs\_to :blahclass, :foreign\_key =\> “myclass”  
end

class Blahclass \< AR::Base  
has\_one :what, :foreign\_key =\> “myclass”  
end

-Derrick S.

---

<div class="post-metadata">

**Author:** ![ddirk](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/d/a9adbd/32.png) [@ddirk](https://www.ruby-forum.com/u/ddirk)\
**Post date:** [April 7, 2006, 2:30pm UTC](https://www.ruby-forum.com/t/has-one-not-using-the-pk/57138/3 "2006-04-07T14:30:51Z")

</div>

Dirk  
\> create table what (  
\> myclass int, ;; references blahclass.blahid  
\> …  
…  
\> I would like to wrap this as  
\> class What \< AR::Base  
\> has\_one :blahclass

It’s in the other direction (a common error):  
class What \< AR::Base  
belongs\_to :blahclass …  
…

When you read ‘belongs\_to’, think ‘references’, ‘points\_to’.

For the details, check ‘has\_one’ and 'belongs\_to methods doc. at  
[http://api.rubyonrails.com/](http://api.rubyonrails.com/)

Alain
