Hi, I’ve been programming in RoR for about a week or 2-3, and I like it
very much.
Now, I have a certain problem that is very complicated, well for me at
least
I have 3 database tables:
recipes
ingredients
and another one which binds the previous 2 tables together
Now, I want to have an input form where you can insert 1 recipe and a
certain amount of ingredients, say 5.
What do I do now: I put in my form.rhtml-file a while loop, which
generates 5 text_fields for the ingredients and i give them each a name
like "ingredient" + i.to_s
Then i can read them out in my create definition in my controller by
doing: params[“ingredient_” + i.to_s]
Ok, first I don’t like this kind code, its way to complicated, and I’m
also running into problems if I want to edit a recipe…
I hope someone knows some better code for this problem…
plus whatever other fields you want, and any HTML, etc.
The helpers like text_field work in this way:
Take the first parameter, and look for an instance variable with
the same name. ‘ingredient’ requires that @ingredient be present.
Call a method on that instance variable with the same name as the
second parameter. In this case, we’re calling @ingredient.name.
Wrap that output in the appropriate HTML, and set the name and id
properties, etc, etc.
Your earlier code didn’t work because it was looking for an instance
variable called “@ingredients[‘0’]”… which isn’t valid or present.
The <% @ingredient = ingredient -%> code above is just making the
current ingredient (which render :partial, :collection passed in)
available as an instance variable; something that the helper methods
require.