rails/rails — Issue #3798: has_many :through join model created twice in after_create in Rails 3.1.3
Author: robmckinnon
Created: 2011-11-29 13:47:01+00:00
State: open

When new has_many :through join model created from after_create filter, the SQL to create join model is executed twice.

The correct behaviour is that it should be executed once.

This problem only occurs when join model created in an after_create filter. When created from a after_save filter, the SQL to create join model is executed only once, which is the correct behaviour.

```ruby
class User < ActiveRecord::Base

has_many :user_groups
has_many :groups, :through => :user_groups

after_create :assign_role

def assign_role
Rails.logger.info "User assign_role called with: #{group_name}"
self.groups << Group.find_by_name(group_name)
Rails.logger.info "Finished user assign_role called with: #{group_name}"
end
end
```

For example, when new User created the SQL to create UserGroup is executed twice, when it should be executed once.

From the log:

(0.5ms) BEGIN

(0.6ms) SELECT 1 FROM "user" WHERE "user"."username" = 'u' LIMIT 1
SQL (0.7ms) INSERT INTO "user" ("algorithm", "created_at", "is_active", "is_super_admin", ...

User assign_role called with: Borrowers

Group Load (0.5ms) SELECT "group".* FROM "group" WHERE "group"."name" = 'Borrowers' LIMIT 1

User Load (0.8ms) SELECT "user".* FROM "user" WHERE "user"."id" = 10336 LIMIT 1

SQL (0.8ms) INSERT INTO "user_group" ("created_at", "group_id", "updated_at", "user_id") VALUES ($1, $2, $3, $4) RETURNING "user_id" [["created_at", Tue, 29 Nov 2011 11:44:57 UTC +00:00], ["group_id", 1], ["updated_at", Tue, 29 Nov 2011 11:44:57 UTC +00:00], ["user_id", 10336]]

Finished user assign_role called with: Borrowers

User Load (0.5ms) SELECT "user".* FROM "user" WHERE "user"."id" = 10336 LIMIT 1
SQL (0.9ms) INSERT INTO "user_group" ("created_at", "group_id", "updated_at", "user_id") VALUES ($1, $2, $3, $4) RETURNING "user_id" [["created_at", Tue, 29 Nov 2011 11:44:57 UTC +00:00], ["group_id", 1], ["updated_at", Tue, 29 Nov 2011 11:44:57 UTC +00:00], ["user_id", 10336]]

PGError: ERROR: duplicate key value violates unique constraint "user_group_pkey"

DETAIL: Key (user_id, group_id)=(10336, 1) already exists.

: INSERT INTO "user_group" ("created_at", "group_id", "updated_at", "user_id") VALUES ($1, $2, $3, $4) RETURNING "user_id"
(0.3ms) ROLLBACK