I have several simple many-to-many relationships in my app. Some use
a join model, and others don’t. Let’s start with one that doesn’t.
class Company < ActiveRecord::Base
Add an industry if it isn’t already there
industry = Industry.find_or_initialize_by_name(name)
self.industries << industry
I have three tables: companies, industries, and companies_industries.
The problem I have is best practices to handle errors with habtm and
Ruby. There are several things that could go wrong here. First,
there should be an update lock on the initial find to ensure that two
processes don’t try to add the same industry. Does :lock => true work
properly here? Normally, I use that where I want to lock a single
row, but that’s not what is happening here.
The next problem is how to get errors from self.industries <<
industry. Both industries and company_industries are inserted into
with this statement. I usually try to use create! and save! in case
there is some db error, but I don’t have that option here. Won’t this
fail silently or by returning nil? If it returns nil, I do I know
What are the best practices for making this bulletproof? Note, I’m
old-school enough want to know what is going on under the covers and
protect my app from it.