2014-09-04 39 views
0

我试图在rails中创建父/子关系关联,但我不太确定如何执行此操作。Ruby on Rails ActiveRecord:使用连接在同一模型中创建父/子关系

我有两个表格,产品和products_products。这两个表格让我有产品和子产品。

products 
----------- 
id | title | ... 

products_products 
----------------- 
id | product_id | parent_product_id | ... 

我想要做的是获得产品的所有儿童产品。

所以我必须:

class Product < ActiveRecord::Base 
    ... 
    has_many :products_products 
    has_many :child_products, through: :products_products, source: :product 
    has_many :parent_products, through: :products_products, source: :parent_product 
    ... 
end 

class ProductsProduct < ActiveRecord::Base 
    .... 
    belongs_to :product 
    belongs_to :parent_product, class_name: "Product", foreign_key: "parent_product_id" 
    .... 
end 

的parent_products协会的工作,但我不知道如何让child_products。

的SQL是:

SELECT "products".* 
FROM "products" 
INNER JOIN "products_products" ON "products"."id" = "products_products"."product_id" 
WHERE "products_products"."parent_product_id" = <myProductd> 

的目标是要能说myProduct.child_products得到的子产品的列表。

+0

对于从业务逻辑的角度来看,你有什么想做的事情,我有点困惑。尽管我会说product_products是一张桌子的糟糕名字。我也错过了为parent_products和child_products定义表的位置。你能否给出一个你想要完成的更详细的例子? – 2014-09-04 19:40:46

+0

基本上,我试图创建一个自引用连接,以便产品可以有子产品。即产品#1可以是产品#2,产品#3等的父母。任何产品可以是任何其他产品的父母。我需要一种方式来获取产品的所有孩子或产品的所有父母的清单。 products_products表只是保存这些关系的连接表。 – 2014-09-04 19:45:31

回答

1

你需要的是一个自我指涉协会。

更改应用程序/模型/ product.rb到:

class Product < ActiveRecord::Base 
    has_many :product_mappings 
    has_many :child_products, :through => :product_mappings 
    has_many :inverse_product_mappings, :class_name => "ProductMapping", :foreign_key => "child_product_id" 
    has_many :inverse_child_products, :through => :inverse_product_mappings, :source => :product 
end 

和应用程序/模型/ product_mapping.rb:

class ProductMapping < ActiveRecord::Base 
    # has product_id, child_product_id 
    belongs_to :product 
    belongs_to :child_product, :class_name => "Product" 
end 

来吧,试试吧:

product = Product.find 1 
product.child_products 

欲了解更多信息,Ryan bates在Self-Referential Association上进行了精彩的截屏。

+0

谢谢。我不得不保留表结构和类名,因为它是一个传统的数据库/应用程序,但你指出了我正确的方向。 – 2014-09-04 21:29:43

相关问题