2010-02-19 43 views
1

尋找實施此場景的最佳方式的一些指導:項目 - 項目關係的Rails模型關聯?

我有一個物品表(的產品),並希望支持交叉銷售/追加銷售/補充物品的能力。所以這裏有一個項目到項目的關係。在這個連接表中,我需要包含鍵之外的其他屬性,例如項目之間的銷售權限(例如,交叉,向上,補充,替代等)。

如何設置模型關聯?

回答

3

通過它的聲音,這個連接表代表了一個全新的模型。我不確定你的要求到底是什麼,但我會發揮出一個潛在的解決方案。現在,讓我們將聯合模型稱爲SalesRelationship。

我要打電話給項目/產品對象「產品」,因爲對我來說,它是一個不太通用的。

的遷移,這將是這個樣子:

class CreateSalesRelationship < ActiveRecord::Migration 
    def self.up 
    create_table :sales_relationship |t| 
     t.string :product_id 
     t.string :other_product_id 
     t.string :type 
     t.timestamps 
    end 
    end 

    def self.down 
    drop_table :sales_relationship 
    end 
end 

您可以包括在遷移所需的任何其他屬性也是如此。接下來,創建一個SalesRelationship模型:

class SalesRelationship < ActiveRecord::Base 
    belongs_to :product 
    belongs_to :other_product, :class_name => "Product 
end 

然後,針對不同類型的關係創建子類:

class CrossSell < SalesRelationship 
end 

class UpSell < SalesRelationship 
end 

class Complement < SalesRelationship 
end 

class Substitute < SalesRelationship 
end 

然後建立在產品型號的關係:

class Product < ActiveRecord::Base 
    has_many :sales_relationships, :dependent => :destroy 
    has_many :cross_sells 
    has_many :up_sells 
    has_many :complements 
    has_many :substitutes 

    has_many :cross_sale_products, :through => :cross_sells, :source => :other_product 
    has_many :up_sale_products, :through => :up_sells, :source => :other_product 
    has_many :complementary_products, :through => :complements, :source => :other_product 
    has_many :substitute_products, :through => :substitutes, :source => :other_product 
end 

現在你應該能夠創建和添加所有你想要的相關產品。

@product1.substitute_products << @product2 
new_product = @product2.complementary_products.build 

對於額外的信用,你可以寫上確保產品永遠不會與自己的SalesRelationship模型簡單的驗證。根據您的要求,這可能需要也可能不需要。

0

事情是這樣的:

has_many :other_item, :class_name => "Item", :through => :item_to_item 

表item_to_item會是這樣的

| item_id | other_item_id | complement | substitute | etc... 

你必須編寫自定義屬性訪問器,這使得確保ITEM_ID總是< other_item_id避免問題與重複。

如果您不太明白我在這裏的意思,請隨時詢問。

+0

是的,您是否真的很好解釋? – keruilin 2010-02-19 01:12:27