I have the following HABTM associations between two models,
MemberEntityAccessibility and MemberEntity:
has_and_belongs_to_many :member_entities,
:class_name => "MemberEntity",
:join_table =>
“accessibilities_member_entities”,
:foreign_key => “accessibility_id”,
:association_foreign_key =>
“member_entity_id”
has_and_belongs_to_many :member_entity_accessibilities,
:class_name => "Accessibility",
:join_table =>
“accessibilities_member_entities”,
:foreign_key => “member_entity_id”,
:association_foreign_key =>
“accessibility_id”
Also in the MemberEntityAccessibility model I have the following code
to allow a member (entity) to be added into the HABTM join table.
def add_member_entity?(entity)
return false if entity.nil? || member_entities.include?
(entity)
member_entities << entity
true
end
When I am testing my code in the test environment (fixtures etc), my
exhaustive(!) logging reveals that ActiveRecord attempts to insert the
same ‘entity’ record twice into the join table when there is only one
member (entity) object in the collection (member_entities). For
example, where an entity object (id=1) is added to ‘member_entities’
of accessibility object (id=1), ActiveRecord saves two records, each
with a compound key of 1,1.
My logging confirms that the member_entities collection only has one
entry (as expected) and not two.
Any ideas would be much appreciated - I have hit a wall with this one
and wonder if it is something to do with the test environment.