views:

48

answers:

1

I'm designing a ruby on rails app for a pharmacy, and one of the features is that there are stores who have pharmacists who work there. In addition, there are pharmacists, who can work at many stores. This sounds like a job for HABTM, right? Well, being the novice I am, I manually designed a workaround (because I never heard of HABTM - I basically taught myself rails and never got to some of the more advanced relationships). Right now, when a pharmacist is saved, there's a couple of lines in the create and update action of the pharmacists controller that turns the stores that they work at into a string, with each store_id separated by a comma. Then, when a store is displayed, it does a MYSQL request by @pharmacists = Pharmacist.find :all, :conditions => "stores REGEXP '#{@store.id}'"

Would moving this system over to a rails based HABTM system be more efficient? Of course it would require less code in the end, but would it be worth it? In other words, what benefits, other than less code, would I get from moving this association to be managed by rails?

+1  A: 

The benefit is that you will be using the right tool for the job! The whole point of using a framework such as Rails is that it helps you solve common problems without having to re-invent the wheel, which is what you've done here. By using associations you'll also be using a relational database properly and can take advantage of benefits like foreign key indexing, which will be faster than string manipulation.

You should use a has_and_belongs_to_many relationship unless you need to store extra attributes on the join model (for example the date a pharmacist started working at a store) in which case use has_many :through.

Using Rails associations will give you all the convenient methods that Rails provides, such as these:

# Find the stores the first pharmacist works at
@stores = Pharmacist.first.stores

# Find the pharmacists who work at a store
@pharmacists = Store.find_by_name('A Store').pharmacists
John Topley
Thanks! I implemented it and it was so easy - it took about 1/5th the code that I used before and was significantly easier than I expected. Those methods that come along with the has_and_belongs_to_many relationship will surly come in handy in future projects, and further down the road with this project.
Eric S.