Has_one not using the pk?

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

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.

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/

Alain

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs