cremes.devlist@mac.com
2006-Jun-21 20:47 UTC
[Rails] how to save objects associated via has_many :through?
I recently converted a habtm relationship into one using has_many :through. Some of my old logic relied on the ability to use the #<< operator to add items to the relationship and get them auto- saved. I''m curious to know the best way to do the same operation with the has_many :through configuration. I looked through the list archives and didn''t find my answer. Rather than post my own models and associations, it''s probably easier to use the example that Josh Susser came up with in this blog post [1]. His example assumes many of these objects are already saved and now need to be joined, so let''s change to the scenario where all 3 separate objects are NEWLY created, joined and saved. Here''s how I think it would work. Please correct me where I''m wrong. # in some controller, assume a form is being passed in to fill out the # Technician and Skill objects def add_technician_with_skills @technician = Technician.new(params[:technician]) @skills = Skills.new(params[:skill]) begin @technician.add_skills(@skills) @technician.save! rescue => err # error handling end # other processing end # in technician.rb model def add_skills(skills) begin cert = Certification.new(:technician => self, :skill => skills, # other fields...) cert.save! rescue => err # error handling end end Will this work? Do I also need to explicitly save @skills or will it be auto-saved via the @technician.save! call? Is the cert.save! call necessary? How do I unwind the cert.save! call if @technician.save! fails? Is there a better way to lay this out so #save failures can be backed out? Thanks for your help. cr [1] http://blog.hasmanythrough.com/articles/read/150