Many-to-many relationship with the same table (Ruby on Rails)

I am working on a Rails application with a product model. I want to be able to connect products with each other. Example: product 1 associated with product 2, product 3, and vice versa. How can I do this in Rails? I was thinking of a connection table, but since I use the same table as point-to-link, I am not sure how this will work.

+3
source share
5 answers

Unchecked and out of memory, I think you need 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 choose to call it) could contain one or more additional fields describing the relationship.

, has_and_belongs_to_many, , "products_products", .

+3

acts_as_follower. http://github.com/tcocca/acts_as_follower/tree/master. .

, . , , 1 2/3 ..

+1

, . , .

, - ProductRelation FirstProduct SecondProduct (, ), , FirstProduct SecondProduct... .

0

: Ruby On Rails -

"- " . :

class Product < ActiveRecord::Base
   ...

   has_many :parent_product_map, class_name: 'ProductMap', foreign_key: 'child_product_id'
   has_many :parent_products, through: :parent_product_map, source: :parent_product, class_name: 'Product'
   has_many :child_product_map, class_name: 'ProductMap', foreign_key: 'parent_product_id'
   has_many :child_products, through: :child_product_map, source: :child_product, class_name: 'Product'
   ...
end

class ProductMap < ActiveRecord::Base
   attr_accessible :child_product_id, :id, :parent_product_id
   belongs_to :child_product, foreign_key: 'child_product_id', class_name: 'Product'
   belongs_to :parent_product, foreign_key: 'parent_product_id', class_name: 'Product'
end

class CreateProductMap < ActiveRecord::Migration
   def change
      create_table :product_maps do |t|
      t.integer :id
      t.timestamps
      t.integer :child_product_id
      t.integer :parent_product_id
    end
 end
0
source

Source: https://habr.com/ru/post/1710345/


All Articles