in Rails, using HABTM, how to avoid multiple INSERTs in join table -


using has_and_belongs_to_many relationship, have following:

model has_and_belongs_to_many :b, :join_table => "a_b" has_and_belongs_to_many :c, :join_table => "a_b"  table a_b a_id b_id c_id 

current behavior:

when doing a.save, 2 insert statements a_b table - a_id set, b_id, set, , c_id = 0, , other a_id , c_id set (no b_id in insert statement). therefore, there 2 rows in join table

desired behavior:

when doing a.save, want 1 insert a_b table, 3 ids set correctly.

how do this?

from understanding (as don't have access change db - legacy), can't use has_many :through on this, join table require id column. if not true, open suggestions.

you might able extension method. you'd still 2 trips db, 1 can update.

has_and_belongs_to_many :b, :join_table => "a_b"   def save    abc = a.find_or_create_by_a_id(self.a_id)    abc.b = self.b    abc.save   end end  has_and_belongs_to_many :c, :join_table => "a_b"   def save    abc = a.find_or_create_by_a_id(self.a_id)    abc.c = self.c    abc.save   end end 

of course, need check if it's new record , handle according. not sure if can redefine save in association extension....


Comments

Popular posts from this blog

java - SNMP4J General Variable Binding Error -

windows - Python Service Installation - "Could not find PythonClass entry" -

Determine if a XmlNode is empty or null in C#? -