2012-10-02 3 views
0

3 개의 다른 HABTM 모델에 3 개의 ID를 저장하는 3 열 조인 테이블이 있습니다.레일 3 - 3 열 결합 테이블 업데이트

모델

# ProductGrade.rb 
has_and_belongs_to_many :vendors, :join_table => "item_codes_product_grades_vendors" 
has_and_belongs_to_many :item_codes, :join_table => "item_codes_product_grades_vendors" 

# Vendor.rb 
has_and_belongs_to_many :prouduct_grades, :join_table => "item_codes_product_grades_vendors" 
has_and_belongs_to_many :item_codes, :join_table => "item_codes_product_grades_vendors" 

# ItemCode.rb 
has_and_belongs_to_many :vendors, :join_table => "item_codes_product_grades_vendors" 
has_and_belongs_to_many :product_grades, :join_table => "item_codes_product_grades_vendors" 

나는 단순히 3 부분으로 협회를 기록 걸려 경우 공급 업체 모델에 대한 사용자 업데이트됩니다.

-- *product_grade_id* -- *vendor_id* -- *item_code_id* -- 
--------------------------------------------------------- 
--    12 --  NULL --    4 -- 
--    12 --   6 --   NULL -- 

내가 실현 :

Vendors_Controller.rb

def update 
    i = ItemCode.find(params[:vendor][:item_codes].to_i) 
    i.vendors << Vendor.find(params[:id]) 
    i.product_grades << ProductGrade.find(params[:product_grade_id]) 

    redirect_to product_grade_vendor_path 
end 

이 올바르게 그러나 다음과 같이 두 가지 기록을 창조하고, 조인 테이블의 데이터의 3 열을 저장 이것은 아마도 어리석은 문법의 문제 일뿐입니다. 그러나 나는 그 값들을 모두 하나의 레코드에 저장하는 방법을 알고 싶습니다.

도움 주셔서 감사합니다.

답변

1

HABTM 대신 has_many :through =>을 사용하는 것이 좋습니다. ActiveRecord는 HABTM의 조인 테이블을 처리 할 수 ​​없지만 has_many :through =>의 조인 테이블을 처리 할 수 ​​있습니다. 나중에 옵션을 사용하면 조인 테이블이 모델로 표시되고 조작, 변경, 업데이트 등의 도구가 제공됩니다.

두 모델을 결합 할 때만 HABTM을 사용하는 것이 좋지만 세 가지가 아닙니다. 그러면 업데이트 방법이 매우 간단해질 것입니다.

def update 
    Association.create!(:product_grade_id => "...", :vendor_id => "...", :item_code_id => "..." 

    redirect_to wherever_path 
end 
+0

알아두면 좋은 점에 대해 조언 해 주셔서 감사합니다. 나는 이것을 구현할 것이고 나는 그것이 작동 할 때 당신에게 돌아 간다. :) – briankulp