2010-02-19 4 views
1

이 시나리오를 구현하는 가장 좋은 방법에 대한 지침을 찾고 있습니다.아이템 - 아이템 관계에 대한 레일스 모델 연관성?

상품 테이블이 있고 제품 ​​교차 판매/상향 판매/보완 기능을 지원하고자합니다. 그래서 여기에 item-to-item (s) 관계가 있습니다. 이 조인 테이블에서 항목 간 sales_relation (예 : 교차, 상향, 보완, 대체 등)과 같은 키 이외의 추가 속성을 포함해야합니다.

모델 연결을 설정하는 방법은 무엇입니까? 이 같은

답변

3

이 소리로 인해이 조인 테이블은 완전히 새로운 모델을 나타냅니다. 귀하의 요구 사항이 정확히 무엇인지는 확실하지 않지만 가능한 해결책을 제시 할 것입니다. 지금은 조인 모델을 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 

: 이것에 대한

마이그레이션은 같을 것입니다.

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 

을 관계의 서로 다른 유형의 하위 클래스를 만든 다음

class SalesRelationship < ActiveRecord::Base 
    belongs_to :product 
    belongs_to :other_product, :class_name => "Product 
end 

: 다음, SalesRelationship 모델을 만들 당신은 당신이 원하는 모든 관련 제품을 만들고 추가 할 수 있어야합니다.

@product1.substitute_products << @product2 
new_product = @product2.complementary_products.build 

추가 크레딧으로 제품이 절대로 자체와 관련이 없는지 확인하는 간단한 유효성 검사를 SalesRelationship 모델에 쓸 수 있습니다. 그것은 귀하의 요구 사항에 따라 필요할 수도 그렇지 않을 수도 있습니다.

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 < 있는지 확인하게 접근 속성 중복 문제.

여기서 내가 의미하는 바를 이해하지 못했다면 더 많은 것을 물어보십시오.

+0

예, 설명해 주셔서 너무 친절하십니까? – keruilin

관련 문제