寻找一些关于实现此场景的最佳方法的指导:
我有一个项目表(产品),并希望支持交叉销售/追加销售/补充项目的能力。因此,这里存在项到项的关系。在此连接表中,我需要包括键以外的其他属性,例如项之间的sales_relation (例如,交叉、向上、互补、替换等)。
如何开始设置模型关联?
发布于 2010-02-20 03:55:42
听起来,这个连接表代表了一个全新的模型。我不确定您的确切需求是什么,但我将展示一个潜在的解决方案。现在,让我们将连接模型称为SalesRelationship。
我将item/product对象称为"products",因为对我来说它不那么通用。
它的迁移过程如下所示:
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-19 08:40:18
如下所示:
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,以避免出现重复项问题。
如果您不太明白我的意思,请随时询问更多问题。
https://stackoverflow.com/questions/2293300
复制相似问题