2012-10-02 50 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