2012-10-02 49 views
0

我有一個3列連接表,它爲3個不同的HABTM模型存儲3個ID。Rails 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部分組成協會當賣方模型中的用戶更新。

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列,但它是建立兩個不同的記錄,像這樣:

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

我知道這可能是一個愚蠢的語法問題,但我只想知道如何讓控制器將這兩個值保存在1條記錄中。

感謝您的幫助!

回答

1

考慮使用has_many :through =>代替HABTM。 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