views:

316

answers:

4

I'm working on a Rails app that has a "products" model. I want to be able to relate products to each other. Example: product 1 related to product 2, product 3, and vice versa. How would I accomplish this in Rails? I was thinking a join table, but since I'm using the same table as the point-of-relationship I'm not sure how that would work.

A: 

You are right, you need a join table. It needs two fields, both of which are foreign keys back to the products table.

So something like ProductRelation table with FirstProduct and SecondProduct fields (there probably is better names for those fields) then you know that FirstProduct is related to SecondProduct... then your queries for related products would be pretty simple.

Max Schmeling
+1  A: 

Untested and from memory, I think you'd want something like this:

class ProductLink < ActiveRecord::Base
  belongs_to :parent_product, :class_name => 'Product'
  belongs_to :child_product, :class_name => 'Product'
end

class Product < ActiveRecord::Base
  has_many :parent_links, :class_name => 'ProductLink', :foreign_key => :parent_product_id
  has_many :child_links, :class_name => 'ProductLink', :foreign_key => :child_product_id
end

ProductLink (or whatever you'd choose to call it) would then be able to contain one or more additional fields that describe the relationship.

You may be able to make it work with has_and_belongs_to_many, although I guess this would require a "products_products" table, which might be a little stressful.

Mike Woodhouse
From memory also, but wouldn't you use has_many :parent_products, :through 'ProductLink' and has_many :child_products, :through 'ProductLink'?
KaptajnKold
A: 

Use the acts_as_follower gem. http://github.com/tcocca/acts_as_follower/tree/master. It is pretty flexible in terms of following relationships and provides a generic following semantics.

Really simple, and works very well. Just use it to say product 1 follows product 2/3 etc.

Ryan Oberoi
A: 

Try the Acts_as_nested-plugin!

http://github.com/rails/acts_as_nested_set/tree/master

Maybe also Rayn Bates screencasts helps you:

http://railscasts.com/episodes/163-self-referential-association

Lichtamberg
I believe the correct URL above should be: http://github.com/rails/acts_as_nested_set
y0mbo