Red Daly
2006-Aug-02 05:59 UTC
[Rails] ActiveRecord: find_or_create with has_and_belongs_to_many --
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 -- Posted via http://www.ruby-forum.com/.
James Mason
2007-Oct-16 20:33 UTC
Re: ActiveRecord: find_or_create with has_and_belongs_to_man
I''ve recently used this form: school.terms << Term.find_or_create_by_code("FALL06") -- Posted via http://www.ruby-forum.com/. --~--~---------~--~----~------------~-------~--~----~ You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group. To post to this group, send email to rubyonrails-talk-/JYPxA39Uh5TLH3MbocFFw@public.gmane.org To unsubscribe from this group, send email to rubyonrails-talk-unsubscribe-/JYPxA39Uh5TLH3MbocFFw@public.gmane.org For more options, visit this group at http://groups.google.com/group/rubyonrails-talk?hl=en -~----------~----~----~----~------~----~------~--~---
Apparently Analagous Threads
- Polymorphic find_or_create bug
- Nested Attributes and find_or_create
- [Patch][Issue #5097] attributeless find_or_create/find_or_initialize
- Parent id for find_or_create method
- 9 commits - libswfdec/swfdec_as_strings.c libswfdec/swfdec_html_parser.c libswfdec/swfdec_style_sheet.c libswfdec/swfdec_style_sheet.h libswfdec/swfdec_text_field_movie_as.c libswfdec/swfdec_text_field_movie.c libswfdec/swfdec_text_field_movie.h