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)
on 2007-01-16 13:16
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
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.