Forum: Ruby on Rails Question about AR associations (belongs_to)

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.
8458ed8e78b2660f8b839f052e20f65f?d=identicon&s=25 Nicolas Blanco (slainer68)
on 2007-01-16 13:16
Hi !

A simple question about belongs_to...

Two models : Upload and Uploadedfile.

In Upload :

belongs_to :uploadedfile, :foreign_key => "file_number_id"

The primary key of Uploads is id, and there is a column named number.

When I try :

upload = Upload.find(1)
upload.uploadedfile

Rails do :
SELECT * FROM uploadedfiles WHERE (uploadedfiles.id = 255)

(255 is the value in file_number_id of course)

But I want Rails to do :
SELECT * FROM uploadedfiles WHERE (uploadedfiles.number = 255)

My question :

In belongs_to, Rails have got a parameter to name the foreign_key in the
current model, but why Rails does not have a parameter to name the
column in the other?
In some case, the column I want to search is not the primary key!

For example I could write :

belongs_to :uploadedfile, :foreign_key => "file_number_id", :column =>
"number"
and it would send :
SELECT * FROM uploadedfiles WHERE (uploadedfiles.number = 255)
4daf0b71d5d9a3882e583c0e72eaf5dc?d=identicon&s=25 Alan Francis (Guest)
on 2007-01-16 15:59
Nicolas Blanco wrote:
> Hi !
>
> A simple question about belongs_to...
>
> Two models : Upload and Uploadedfile.

Hmmm :-)

So a few things to note:

1) the belongs_to goes in the 'child' record.  ie. the record with the
foreign key.   Person belongs_to :team  ( the person table would have id
and team_id )

I'm thinking you should probably have UploadedFile belongs_to :upload
and have an upload_id in UploadedFile.

2) Associations work like foreign keys, and so generally should 'point'
to a primary key (usually 'id').

So with tables:

uploads( id, number, name, whatever)
uploaded_files( id, upload_id, filename, whatever)

and models

Upload
  has_one :uploaded_file

UploadedFile
  belongs_to :upload

You should be set....I think.


Does this help ?

Alan
4daf0b71d5d9a3882e583c0e72eaf5dc?d=identicon&s=25 Alan Francis (Guest)
on 2007-01-16 16:01
Alan Francis wrote:

> So with tables:
>
> uploads( id, number, name, whatever)
> uploaded_files( id, upload_id, filename, whatever)
>
> and models
>
> Upload
>   has_one :uploaded_file
>
> UploadedFile
>   belongs_to :upload
>

I forgot to add :-)

You can now do

@upload = Upload.find_by_number( aNumber )
@upload.uploaded_file

or

@upload = Upload.find(1)
@upload.uploaded_file

A.
This topic is locked and can not be replied to.