I have a 3 column join table that is storing 3 ID’s for 3 different HABTM models.
Models
# 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"
I am simply wanting to record the 3-part association when a user updates on the Vendor model.
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
This correctly saves the 3 columns of data in the join table, however it is creating two-different records, like this:
-- *product_grade_id* -- *vendor_id* -- *item_code_id* --
---------------------------------------------------------
-- 12 -- NULL -- 4 --
-- 12 -- 6 -- NULL --
I realize this is probably a silly syntax issue, but I just want to know how to get the controller to save both of those values in 1 record.
Thanks for the help!
Consider using
has_many :through =>instead of HABTM. ActiveRecord can’t address join tables in HABTM but it can address join tables inhas_many :through =>. With the later option, the join table will be represented as a model and you will be given tools how to manipulate it, change it, update it, etc.I recommend using HABTM only when you are joining two models, but not three. Your update method will then be very much simplified.