0

Using a has_and_belongs_to_many relationship, I have the following:

model A
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, I get 2 insert statements into the A_B table - A_id is set, B_id, is set, and C_id = 0, and the other where all only A_id and C_id are set (no B_id in the INSERT statement). Therefore, there are 2 rows in my JOIN table

Desired behavior:

when doing A.save, I want 1 INSERT into A_B table, where all 3 ids are set correctly.

How do I do this?

From my understanding (as I don't really have access to change the db - legacy), I can't use has_many :through on this, as the JOIN table would require an id column. If that is not true, I am open to any suggestions.

MikeP
  • 1

1 Answers1

0

You might be able to do this with an extension method. You'd probably still get the 2 trips to the DB, but one can be an update.

has_and_belongs_to_many :B, :join_table => "A_B" do
  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" do
  def save
   abc = A.find_or_create_by_a_id(self.a_id)
   abc.c = self.c
   abc.save
  end
end

Of course, you need to check if it's a new record and handle according. Not sure if you can redefine save in an association extension....

Jeff Paquette
  • 7,089
  • 2
  • 31
  • 40