Destroy_all and has_and_belongs_to_many

I have a single class with a many-to-many relationship to itself.

class Connection

has_and_belongs_to_many :matches,
:class_name => “Connection”,
:join_table => “matched_connections”,
:foreign_key => “connection_id”,
:association_foreign_key => “match_id”

has_and_belongs_to_many :requests,
:class_name => “Connection”,
:join_table => “matched_connections”,
:foreign_key => “match_id”,
:association_foreign_key => “connection_id”
end

I want to be able to destroy all the matches without deleting the
dependent connections. Essentially, I want to remove all the entries in
matched_connections that have the correct connection_id. However, if I
run:

con.matches.destroy_all

It deletes the con object as well. I can’t add :dependent to the habtm,
so I how do I only destroy the rows in matched_connections and still
keep the objects in sync?

Use has:_many :through

class MatchedConnection

This is your Join Table, now as a real Model. The Table also now

should have an primary key “id” column

belongs_to: matching_connection, :class_name =>
“Connection”, :foreign_key => “match_id”
belongs_to: requesting_connnection, :class_name =>
“Connection”, :foreign_key => “request_id”

end

class Connection

a Request connection has these associations to its corresponding

matches:
has_many :match_connections, :class_name => “MatchedConnection”,
foreign_key => “request_id”
has_many :matches,
:through => :match_connections,
:class_name => “Connection”
:foreign_key => “match_id”

a Match connection has these associations to its corresponding

requests:
has_many :requested_connections, :class_name =>
“MatchedConnection”, :foreign_key => “match_id”
has_many :requests,
:through => :request_connections,
:class_name => “Connection”
:foreign_key => “request_id”
end

Explanation:

From a connection on the Match side to the request side:
->(match_id ) request_connections (request_id) → requests
From a connection on the request side to the Match side:
->(request_id ) request_connections (match_id) → requests

As the join Table now is a real model, you can access the join items:
@Con = Connection.find(1)
@con.match_connections.destroy_all

don’t let the names of the associations i used confuse you, i don’t
know exactly what your Models should do, so the naming could be a
little inconvinient.

On 12 Jun., 05:21, Dave D. [email protected]

My explanation is a little wrong, no time to correct it atm. Code
should be fine though, just check it out.

Thanks, I was able to make this work elsewhere in my app using the same
technique, but I guess habtm always wants to destroy dependencies. I
also tried

con.matches.delete(all)
con.matches.reload

That seemed to work as well, but I wasn’t sure of the side effects.