Erik A. Hanson's Weblog

Join Tables with Attributes in Rails

Posted: February 12th, 2006    Tags: Howto, Ruby on Rails

I 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.



2 Responses to “Join Tables with Attributes in Rails”

  1. werutzb Says:

    Hi!

    I would like extend my SQL capabilities.
    I red that many SQL books and would like to
    read more about SQL for my occupation as mysql database manager.

    What can you recommend?

    Thanks,
    Werutz

  2. Erik Says:

    I don’t have any specific recommendations. Mostly, I use Google and pair programming to learn about SQL :)

Leave a Reply



(Comments are moderated to keep out spam. Please be patient.)