Table belongs_to either of two other tables?


#1

Suppose I have a site about books and authors, and users can leave
comments on either a book or an author.

I’d want to have a table called “comments”, which could belong to either
an author OR a book.

In my structure I wouldn’t be sure whether to include an “author_id” or
a “book_id”, or both.

What would be the best way to handle this relationship?

Thanks in advance for any help,

Jeff


#2

look at polymorphic associations in redgerails…

On Sunday, March 19, 2006, at 4:46 PM, Jeff C.man wrote:

What would be the best way to handle this relationship?
http://lists.rubyonrails.org/mailman/listinfo/rails
Mikkel B.

www.strongside.dk - Football Portal(DK)
nflfeed.helenius.org - Football News(DK)
ting.minline.dk - Buy Old Stuff!(DK)


#3

Thanks, that looks like just the thing!

Jeff

Mikkel B. wrote:

look at polymorphic associations in redgerails…

On Sunday, March 19, 2006, at 4:46 PM, Jeff C.man wrote:

What would be the best way to handle this relationship?
http://lists.rubyonrails.org/mailman/listinfo/rails
Mikkel B.

www.strongside.dk - Football Portal(DK)
nflfeed.helenius.org - Football News(DK)
ting.minline.dk - Buy Old Stuff!(DK)


#4

Am Sonntag, den 19.03.2006, 16:46 +0100 schrieb Jeff C.man:

Suppose I have a site about books and authors, and users can leave
comments on either a book or an author.

I’d want to have a table called “comments”, which could belong to either
an author OR a book.

In my structure I wouldn’t be sure whether to include an “author_id” or
a “book_id”, or both.

What would be the best way to handle this relationship?

class Book < ActiveRecord::Base
has_many :comments
end

class Author < ActiveRecord::Base
has_many :comments
end

class Comment < ActiveRecord::Base
belongs_to :book
belongs_to :author
end

In your comments table include a book_id and an author_id field.


Norman T.

http://blog.inlet-media.de