# Mysql error on scoped find\_or\_create\_by\_attr

**URL:** <https://www.ruby-forum.com/t/mysql-error-on-scoped-find-or-create-by-attr/163659>\
**Category:** Rails\
**Created:** [March 23, 2009, 6:36pm UTC](https://www.ruby-forum.com/t/mysql-error-on-scoped-find-or-create-by-attr/163659 "2009-03-23T18:36:51Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![klochner](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/k/ad7895/32.png) [@klochner](https://www.ruby-forum.com/u/klochner)\
**Post date:** [March 23, 2009, 6:36pm UTC](https://www.ruby-forum.com/t/mysql-error-on-scoped-find-or-create-by-attr/163659/1 "2009-03-23T18:36:51Z")

</div>

Anyone have insight on this one?

class Parent  
has\_many :children  
end

add\_index “children”, [“parent\_id”, “name”], :name =\>  
“by\_parent\_name”, :unique =\> true

a = Parent.find(1)  
a.children.find\_or\_create\_by\_name “foobar”

Mysql::Error: Duplicate entry ‘foobar’ for key 2: INSERT INTO  
`children` (`name`, `updated_at`, `parent_id`, `created_at`) VALUES  
(“foobar”, ‘2009-03-23 17:25:39’, 1, ‘2009-03-23 17:25:39’)

---

<div class="post-metadata">

**Author:** ![klochner](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/k/ad7895/32.png) [@klochner](https://www.ruby-forum.com/u/klochner)\
**Post date:** [March 23, 2009, 7:12pm UTC](https://www.ruby-forum.com/t/mysql-error-on-scoped-find-or-create-by-attr/163659/2 "2009-03-23T19:12:08Z")

</div>

The name ‘foobar’ exists already?

---

<div class="post-metadata">

**Author:** ![klochner](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/k/ad7895/32.png) [@klochner](https://www.ruby-forum.com/u/klochner)\
**Post date:** [March 23, 2009, 7:16pm UTC](https://www.ruby-forum.com/t/mysql-error-on-scoped-find-or-create-by-attr/163659/3 "2009-03-23T19:16:53Z")

</div>

but the point is that it’s a find\_or\_create, and the index is on  
[:parent\_id,:name],  
so it should just find the record if it’s a duplicate.

Also, the following worked:

Child.find\_or\_create\_by\_parent\_id\_and\_name(1,“foobar”)
