Join Tables with Attributes in Rails
Posted: February 12th, 2006 Tags: Howto, Ruby on RailsI had a little trouble today with join tables that contain attributes.
Creating the join table
Starting with tables foos and bars, I created a join table bars_foos. (Rails expects the join table’s name to be a concatenation of the two table names in alphabetical order).
Reading attributes
I added an attribute baz to bars_foos. I had originally tried to access it with:
myFoo.baz
but that didn’t work. It turns out that I needed to force Rails to do the join before accessing the attribute, which makes sense when you think about it (but it took me a while before my little brain thought about it correctly):
myFoo.bars.baz
Adding attributes
Use the well-documented push_with_attributes method:
myFoo.bars.push_with_attributes(bar, :baz => "fez")
Updating attributes
Apparently you can’t. Luckily, in my app the attribute is immutable. Other people have suggested deleting and re-inserting the row which I imagine shouldn’t be a problem for most applications.