rails/rails — Issue #5325: find_or_create_ fails on many-to-many association
Author: yjchen
Created: 2012-03-07 14:04:56+00:00
State: open

I have a model Photo and Face with many-to-many association like this:

```ruby
class Photo < ActiveRecord::Base
belongs_to :user
has_many :ownerships
has_many :faces, :through => :ownerships
end
```
```ruby
class Face < ActiveRecord::Base
has_many :ownerships
has_many :photos, :through => :ownerships
end
```
```ruby
class Ownership < ActiveRecord::Base
belongs_to :face
belongs_to :photo
end
```
Use find_or_create create associated object twice:
```
1.9.3-p125 :003 > photo.faces.find_or_create_by_name('Tim')
Face Load (1.1ms) SELECT "faces".* FROM "faces" INNER JOIN "ownerships" ON "faces"."id" = "ownerships"."face_id" WHERE "ownerships"."photo_id" = 1 AND "faces"."name" = 'Tim' LIMIT 1
(0.1ms) begin transaction
SQL (42.5ms) INSERT INTO "faces" ("created_at", "name", "updated_at") VALUES (?, ?, ?) [["created_at", Wed, 07 Mar 2012 14:01:41 UTC +00:00], ["name", "Tim"], ["updated_at", Wed, 07 Mar 2012 14:01:41 UTC +00:00]]
(3.0ms) commit transaction
Face Load (0.4ms) SELECT "faces".* FROM "faces" INNER JOIN "ownerships" ON "faces"."id" = "ownerships"."face_id" WHERE "ownerships"."photo_id" = 1 AND "faces"."name" = 'Tim' LIMIT 1
(0.1ms) begin transaction
SQL (0.6ms) INSERT INTO "faces" ("created_at", "name", "updated_at") VALUES (?, ?, ?) [["created_at", Wed, 07 Mar 2012 14:01:41 UTC +00:00], ["name", "Tim"], ["updated_at", Wed, 07 Mar 2012 14:01:41 UTC +00:00]]
(2.7ms) commit transaction
=> #
```

This runs on Rails 3.2.1.