【问题标题】:Rails Model Associations for Item-Item Relationship?项目-项目关系的 Rails 模型关联?
【发布时间】:2010-02-19 00:29:15
【问题描述】:

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

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

如何设置模型关联?

【问题讨论】:

    标签: ruby associations models rails-models


    【解决方案1】:

    听起来,这个连接表代表了一个全新的模型。我不确定您的具体要求是什么,但我会提出一种潜在的解决方案。现在,我们将连接模型称为 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 模型上编写一个简单的验证,以确保产品永远不会与自身相关。这可能是必要的,也可能不是必要的,这取决于您的要求。

    【讨论】:

      【解决方案2】:

      类似这样的:

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

      表 item_to_item 会这样

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

      您必须编写一个自定义属性访问器,确保 item_id 始终为

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

      【讨论】:

      • 是的,请问您好心解释一下吗?
      猜你喜欢
      • 1970-01-01
      • 2013-02-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-21
      • 2013-03-21
      • 2018-04-05
      • 2015-12-24
      相关资源
      最近更新 更多