首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >项目-项目关系的Rails模型关联?

项目-项目关系的Rails模型关联?
EN

Stack Overflow用户
提问于 2010-02-19 08:29:15
回答 2查看 309关注 0票数 1

寻找一些关于实现此场景的最佳方法的指导:

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

如何开始设置模型关联?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2010-02-20 03:55:42

听起来,这个连接表代表了一个全新的模型。我不确定您的确切需求是什么,但我将展示一个潜在的解决方案。现在,让我们将连接模型称为SalesRelationship。

我将item/product对象称为"products",因为对我来说它不那么通用。

它的迁移过程如下所示:

代码语言:javascript
复制
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模型:

代码语言:javascript
复制
class SalesRelationship < ActiveRecord::Base
  belongs_to :product
  belongs_to :other_product, :class_name => "Product
end

然后,为不同类型的关系创建子类:

代码语言:javascript
复制
class CrossSell < SalesRelationship
end

class UpSell < SalesRelationship
end

class Complement < SalesRelationship
end

class Substitute < SalesRelationship
end

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

代码语言:javascript
复制
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

现在,您应该能够创建和添加您想要的所有相关产品。

代码语言:javascript
复制
@product1.substitute_products << @product2
new_product = @product2.complementary_products.build

为了获得额外的好处,您可以在SalesRelationship模型上编写一个简单的验证,以确保产品永远不会与其本身相关。这可能是必要的,也可能不是必要的,这取决于您的需求。

票数 3
EN

Stack Overflow用户

发布于 2010-02-19 08:40:18

如下所示:

代码语言:javascript
复制
has_many :other_item, :class_name => "Item", :through => :item_to_item

表item_to_item应该是这样的

代码语言:javascript
复制
| item_id | other_item_id | complement | substitute | etc...

您必须编写一个自定义属性访问器,以确保item_id始终为< other_item_id,以避免出现重复项问题。

如果您不太明白我的意思,请随时询问更多问题。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/2293300

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档