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 S. 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])
@skills =[:skill])
rescue => err
# error handling

other processing


in technician.rb model

def add_skills(skills)
cert = => self,
:skill => skills,
# other fields…)!
rescue => err
# error handling

Will this work? Do I also need to explicitly save @skills or will it
be auto-saved via the! call? Is the! call

How do I unwind the! call if! fails?

Is there a better way to lay this out so #save failures can be backed

Thanks for your help.



This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs