Forum: Ruby on Rails Table belongs_to either of two other tables?

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.
59ea1b450935b9d70abfec4186b7a4d5?d=identicon&s=25 Jeff Coleman (progressions)
on 2006-03-19 16:46
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
5d15c6821f3c3054c04b85471824ba7c?d=identicon&s=25 Mikkel Bruun (Guest)
on 2006-03-19 17:08
(Received via mailing list)
look at polymorphic associations in redgerails...

On Sunday, March 19, 2006, at 4:46 PM, Jeff Coleman wrote:
>What would be the best way to handle this relationship?
>http://lists.rubyonrails.org/mailman/listinfo/rails
Mikkel Bruun

www.strongside.dk    - Football Portal(DK)
nflfeed.helenius.org - Football News(DK)
ting.minline.dk      - Buy Old Stuff!(DK)
59ea1b450935b9d70abfec4186b7a4d5?d=identicon&s=25 Jeff Coleman (progressions)
on 2006-03-20 02:41
Thanks, that looks like just the thing!

Jeff

Mikkel Bruun wrote:
> look at polymorphic associations in redgerails...
>
> On Sunday, March 19, 2006, at 4:46 PM, Jeff Coleman wrote:
>>What would be the best way to handle this relationship?
>>http://lists.rubyonrails.org/mailman/listinfo/rails
> Mikkel Bruun
>
> www.strongside.dk    - Football Portal(DK)
> nflfeed.helenius.org - Football News(DK)
> ting.minline.dk      - Buy Old Stuff!(DK)
Bf66e10c8fc4abefebde0425e7f6f15a?d=identicon&s=25 Norman Timmler (Guest)
on 2006-03-20 10:43
(Received via mailing list)
Am Sonntag, den 19.03.2006, 16:46 +0100 schrieb Jeff Coleman:
> 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 Timmler

http://blog.inlet-media.de
This topic is locked and can not be replied to.