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.
Jeff C. (Guest)
on 2006-03-19 17: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
Mikkel B. (Guest)
on 2006-03-19 18:08
(Received via mailing list)
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)
Jeff C. (Guest)
on 2006-03-20 03:41
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)
Norman T. (Guest)
on 2006-03-20 11:43
(Received via mailing list)
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
This topic is locked and can not be replied to.