views:

32

answers:

1

Hey folks,

I'm just learning rails and I've run into a bit of a snag. Let me start with a simple breakdown of my application - it's a cookbook (of sorts)

  • Recipes have one or more ingredients (tuna, spleens, etc)
  • Ingredients have one unit (ounces, pounds, etc)
  • Units are pulled from a lookup table

Here's a screenshot to help clarify things further: Form Mockup

Here's my issue: my collection_select elements names should be something like unit[id][]

Instead, they're all just named unit[id]. Here's the snippet I'm using:

collection_select(
    :unit, 
    :id, 
    @units, 
    :id, 
    :name, 
    options = {
        :prompt => "Please Select", 
        :class => "ingredient_unit",
        :name => "unit[][]",
        :id => "unit:" + i.to_s()
    }
);

However, this is what it is outputting:

<select id="unit_id" name="unit[id]">
<option value="">Please Select</option>
<option value="1">Ounces</option>
</select>
...

Now, in php, these dropdowns would be named unit[]. Am I going about this the wrong way?

Thanks for the help

A: 

I am not sure what the "name" option does in the "options" hash. Can you post a link to where you found documentation of that? It looks like you are using the collection select helper properly. What do you mean by "these drop downs would be named unit[]"? It might help if you tell us your end goal of this form as Rails usually just handles stuff for you. Take advantage of its magic.

Also if you are a Rails beginner, highly recommend checking out Ryan Bates' screencasts on complex forms. Here is the link to part 1: http://railscasts.com/episodes/73-complex-forms-part-1

Tony
Thanks for the link, it helped A LOT. As for the `:name` parameter, it was more of an assumption. With other form helpers, you can pass in `:name` to set the name of the text input or whatnot. As for my goal of the form, it was to create a new recipe and assign ingredients to that recipe, and units to each ingredient. As for the `unit[]` remark: in PHP, if you want to specify an array of form elements, you append `[]` to the end of the element name and then `$_POST` will treat `$_POST["unit"]` as an array. I hope that helps.
Levi Hackwith
Just a warning, the code from some of the things that he talks about has been superseded by nested attributes. http://railscasts.com/episodes/196-nested-model-form-part-1
Steve Klabnik