Forum: Ruby on Rails Foreign-key confusion

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.
Db9cd94b67668e3d0cc745ef293759ea?d=identicon&s=25 Ad Richards (arichards)
on 2009-02-21 14:22
Hi,

I am a bit confused about managing the relationship between two of my
tables:

I have developed a script using scRUBYt that scrapes data from a website
and dumps the following four fields into my Shows table:

class CreateShows
create table :shows do |t|
   t.string :date
   t.string :venue
   t.string :info
   t.string :comics

The second table I created is called Theatres:

class CreateTheatres
create table :theatres do |t|
   t.string :name
   t.string :address
   t.string :website_url
   t.string :location

The :venue field in the Shows table corresponds to the :name field in
the Theatres table. How do I set up a relationship whereby Theatres have
many shows, while defining this (:venue - :name) relationship as the
link?

I have tried the :set_primary_key & :foreign_key => ... methods without
success.
Does the primary or foreign key always have to be an integer?

Any suggestions would be much appreciated..
81b61875e41eaa58887543635d556fca?d=identicon&s=25 Frederick Cheung (Guest)
on 2009-02-21 15:04
(Received via mailing list)
On 21 Feb 2009, at 13:22, Ad Richards wrote:

> class CreateShows
>   t.string :name
> I have tried the :set_primary_key & :foreign_key => ... methods
> without
> success.
> Does the primary or foreign key always have to be an integer?
>
A belongs_to relationship has to go through the primary key of the
other model and setting the primary key of theatres to be the name
would be a bad thing (eg what if two towns had a theatre by the same
name).
The rails way would be to do away with the venue column and have a
theatre_id one instead
Db9cd94b67668e3d0cc745ef293759ea?d=identicon&s=25 Ad Richards (arichards)
on 2009-02-21 19:31
Thanks Fred,

I took your advice and added a theatre_id column to the Shows table.

Then I added the following callback to the Shows model, in order to
automatically update the :theatre_id column with the id of the
corresponding theatre in the Theatres table.

class Show < ActiveRecord::Base
belongs_to :theatre

after_create :build_theatre_ids

def build_theatre_ids
  t = Theatre.find_by_name(self.venue)
  self.update_attributes(:theatre_id => t.id) rescue nil
end
end

And it works a treat!
This topic is locked and can not be replied to.