Topic: Belonging to multiple types

Hi,

Is it possible to specify that something belongs to either one type or another type? For instance a review might belong to many things suchs as a book or a cd or a bike or ... Is it possible to specify this kind of relationship or is it better to have a bookreview-type, a cdreview-type, a bikereview-type etc.?

TIA
Thomas

Re: Belonging to multiple types

It's up to your design, but frankly "boorreview-type" smells bad design to me :-)

The simplest might be:

reviews:
belongs_to :type

types:
has_many :reviews


Or more complex, where both review can have many types and vice versa:

review:
has_many :types, :through => :review_types
has_many :review_types

review_types:
belongs_to :review
belongs_to :type

type
has_many :reviews, :through => :review_types
has_many :review_types

Or actually I recommend to read
http://blog.hasmanythrough.com/articles … sociations
where you will find a lot's of good info about associations.

Priit

Last edited by Priit (2006-10-29 03:55:37)

Estonian ruby coders => http://ruby.ee

Re: Belonging to multiple types

Thanks,

I don't want to do bad design :-) What would you recommend?

TIA
Thomas

Re: Belonging to multiple types

Sounds like polymorphic association is what you want. In your case you would do this:

# schema
create_table :reviews do |t|
  t.column :product_id, :integer
  t.column :product_type, :string
  t.column :content, :text
end

# model
class Review < ActiveRecord::Base
  belongs_to :product, :polymorphic => true
end


Rails does a little magic here and uses the "product_type" column to define the model of the product - no "Product" model exists. So, if you call @review.product it might return a Book class, or a Bike class, or whatever "product" it belongs to. You need to set this association up on the other side as well. Like this:

class Book < ActiveRecord::Base
  has_many :reviews, :as => :product
end

class Bike < ActiveRecord::Base
  has_many :reviews, :as => :product
end


Here you can call @book.reviews or @bike.reviews and it will return all reviews with the correct product_id and product_type associated. If you need further explanation, feel free to ask.

Railscasts - Free Ruby on Rails Screencasts