1

このシナリオを実装するための最良の方法に関するガイダンスを探しています。

(製品の)アイテムテーブルがあり、アイテムのクロスセル/アップセル/補完機能をサポートしたいと考えています。したがって、ここにはアイテム間の関係があります。この結合テーブルには、アイテム間のsales_relationなどのキー以外の追加の属性(たとえば、cross、up、complement、substituteなど)を含める必要があります。

モデルの関連付けを設定するにはどうすればよいですか?

4

2 に答える 2

3

その音からすると、この結合テーブルはまったく新しいモデルを表しています。あなたの要件が正確に何であるかはわかりませんが、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

次に、製品モデルで関係を設定します。

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 に答える