寻找实施此场景的最佳方式的一些指导:项目 - 项目关系的Rails模型关联?
我有一个物品表(的产品),并希望支持交叉销售/追加销售/补充物品的能力。所以这里有一个项目到项目的关系。在这个连接表中,我需要包含键之外的其他属性,例如项目之间的销售权限(例如,交叉,向上,补充,替代等)。
如何设置模型关联?
寻找实施此场景的最佳方式的一些指导:项目 - 项目关系的Rails模型关联?
我有一个物品表(的产品),并希望支持交叉销售/追加销售/补充物品的能力。所以这里有一个项目到项目的关系。在这个连接表中,我需要包含键之外的其他属性,例如项目之间的销售权限(例如,交叉,向上,补充,替代等)。
如何设置模型关联?
通过它的声音,这个连接表代表了一个全新的模型。我不确定你的要求到底是什么,但我会发挥出一个潜在的解决方案。现在,让我们将联合模型称为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模型简单的验证。根据您的要求,这可能需要也可能不需要。
事情是这样的:
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避免问题与重复。
如果您不太明白我在这里的意思,请随时询问。
是的,您是否真的很好解释? – keruilin 2010-02-19 01:12:27