# ActiveRecord: find\_or\_create with has\_and\_belongs\_to\_many --

**URL:** <https://www.ruby-forum.com/t/activerecord-find-or-create-with-has-and-belongs-to-many/100858>\
**Category:** Ruby\
**Created:** [August 1, 2006, 4:28pm UTC](https://www.ruby-forum.com/t/activerecord-find-or-create-with-has-and-belongs-to-many/100858 "2006-08-01T16:28:14Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![Red\_Daly](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/r/e0b2c6/32.png) [@Red\_Daly](https://www.ruby-forum.com/u/Red_Daly)\
**Post date:** [August 1, 2006, 4:28pm UTC](https://www.ruby-forum.com/t/activerecord-find-or-create-with-has-and-belongs-to-many/100858/1 "2006-08-01T16:28:14Z")

</div>

I am attempting to use find\_or\_create on a foreign table with a  
has\_and\_belongs\_to\_many relationship with my current table. I am doing  
the following:

term = school.terms.find\_or\_create\_by\_code(“FALL06”)

the queries in the log show the expected SELECT statement to query if  
there is a join table record between the school and term with code  
“FALL06”:

SELECT \* FROM term  
INNER JOIN school\_term ON term.id = school\_term.term\_id  
WHERE (school\_term.school\_id = 1 )  
AND (term.`code` = ‘FALL06’ )  
LIMIT 1

but the INSERT behavior does not include a join table insert if the  
SELECT does not find an appropriate record:

INSERT INTO term (`code`, `name_full`, `name_common`, `date_end`,  
`date_start`)  
VALUES(‘FALL06’, NULL, NULL, NULL, NULL)

I have resolved this by changing my original code to implement a  
uniqueness check in ruby:

term = school.terms.find\_or\_create\_by\_code(“FALL06”)  
school.terms \<\< term unless school.terms.any? do |i| i == term;

It seems like ActiveRecord and SQL should take care of that behavior  
rather than the ActiveRecord implementor and Ruby. Am I missing  
something? Is there another way to do what I want?

Also, I’m not sure if c.l.ruby is the best newsgroup, but I couldn’t  
find a ruby on rails group.

Thanks Sincerely,  
Red Daly

---

<div class="post-metadata">

**Author:** ![Red\_Daly](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/r/e0b2c6/32.png) [@Red\_Daly](https://www.ruby-forum.com/u/Red_Daly)\
**Post date:** [August 1, 2006, 4:35pm UTC](https://www.ruby-forum.com/t/activerecord-find-or-create-with-has-and-belongs-to-many/100858/2 "2006-08-01T16:35:23Z")

</div>

On Aug 1, 2006, at 10:25 AM, Red Daly wrote:

> Also, I’m not sure if c.l.ruby is the best newsgroup, but I  
> couldn’t find a ruby on rails group.

You want the rails mailing list:  
[http://lists.rubyonrails.org/mailman/listinfo/rails](http://lists.rubyonrails.org/mailman/listinfo/rails)

If you don’t want to deal with lots of email traffic, there a web  
gateway to it at  
[http://www.ruby-forum.com/](http://www.ruby-forum.com/)
