You are viewing a read-only archive of the Blogs.Harvard network. Learn more.

What Genius Created Checkboxes?

August 16th, 2010

Good workout. Thanks for asking. Felt so yummy to be back in the gym. Wish my husband didn’t have evening clients so I could do it more often.

Unfortunately, my husband’s sporadic schedule combined with my kids’ relentless bedtime ritual means it’s impossible for me to keep a regimen going. Which is really ironic when you consider that he’s a personal trainer.

Anyway, back to rails related stuff…. I am freaking amazed how I learn something new with each episode. Tonight, I watched episode #17: HABTM (Has And Belongs To Many) Checkboxes.

Did you know that simply passing an array of values to your foreign key will auto-populate your join table? Ryan’s example illustrates this nicely via script/console:

>> p = Product.find(:first)
>> p.category_ids = [2, 3]

This code above automatically created the SQL insert statement below:

INSERT INTO categories_products('product_id', 'category_id') 
VALUES(1, 2)

Of course this only works with HABTM. You’re outta luck with Has Many Through and gotta roll your own. Still, this little shortcut is kinda nifty.

By the way… don’t you just HATE that empty checkboxes return NOTHING in HTML. In other words, when the checkbox is not checked no value is sent.

What a PAIN IN THE ASS! Sure there are ways to get around this, but what genius thought this up?

Yeah okay, there’s most likely some serious reason why this must be… but all I know is that I have to jump through stupid hoops and make an extra database call to get this to work properly. LAME!

Entry Filed under: Professional,Railscasts Project,Ruby on Rails

4 Comments Add your own

  • 1. John Woodell  |  August 21st, 2010 at 11:14 pm

    I have always found this annoying as well. Once I got DataMapper working with Rails 2.3, I was pleasantly surprised that this problem went away. I think it has to do with the way your schema is defined in your model, so this sort of thing is possible.

  • 2. Ed Baxter  |  September 29th, 2010 at 6:33 am

    I feel your pain my friend! Like John said it could be to do with your schema, i’ve yet to find a solution but I will keep trying!

  • 3. lianaleahy  |  September 29th, 2010 at 9:01 am

    Actually, this is an HTML thing. When the checkbox is not checked no value is sent. As opposed to doing something rational like returning 1 when checked and 0 when not checked.

    I’ve never played with DataMapper…Checked the website but I’m still not really sure why I need this.

  • 4. My Baby Can Read Reviews  |  November 24th, 2010 at 9:57 pm

    Where can I find a DataMapper>?

Leave a Comment

Required

Required, hidden

Some HTML allowed:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>