1

寻找有关实施此方案的最佳方法的一些指导:

我有一个项目表(产品),并希望支持交叉销售/追加销售/补充项目的能力。所以这里有一个项目到项目的关系。在这个连接表中,我需要包括键之外的其他属性,例如项目之间的 sales_relation(例如,交叉、向上、补充、替代等)。

如何设置模型关联?

4

2 回答 2

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

然后在 Product 模型上设置关系:

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 模型上编写一个简单的验证,以确保产品永远不会与自身相关。这可能是必要的,也可能不是必要的,具体取决于您的要求。

于 2010-02-19T19:55:41.820 回答
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 以避免重复问题。

如果您不太明白我在这里的意思,请随时询问更多信息。

于 2010-02-19T00:40:18.107 回答