Ooh_Gravy wrote:
Hey there,
I'm new to Rails and am learning by trying to write a cookbook
application. My question is about the best way to implement adding
multiple steps to a recipe.
Imagine I have a recipe that has a title, author, description and a
number of steps/instructions. Instead of entering all the steps in a
single text box, I'd like to have the user enter each step
individually so that I can later list all steps on one page or skip
through them one per page, for example.
I'm assuming that the way to do this is to have a separate table that
holds the steps for each recipe, similar to the posts/comments
relationship in all the blog examples. However, is there a way of
implementing this such that a user could add all the recipe details
and steps on one page rather than entering the details first and each
step on subsequent table saves?
Does that make any sense? Maybe it's a silly way of trying to
implement a recipe book in the first place? Thoughts?
I don't think it's silly at all. It's how I would approach this myself.
From the controller/model aspect this is pretty straight forward. For
each step you would add them like so: recipe.steps << new_step.
The view is where these things get a little more tricky. There is no
"one right way" to do this. It's going to depend on your specific case.
Often it's a good idea to allow the user to add steps by using AJAX to
insert new form fields to hold all the steps the user may want to enter.
Another possible approach (and one I might consider in this specific
case) would be to allow the user to enter all the instructions (steps)
into a single text area. Then using some basic markup that would allow
you to separate each step and store them individually into the steps
table. It really depends on what ends up to be the best user experience.
I would try to avoid having to refresh the entire page while adding
additional steps. That generally does not provide a great user
experience, but it is a option. It's only real advantage would be that
it would require no JavaScript to work (and so may be okay as a UI
degradation for when JS is not available).
The down-side to the single text area approach is that you would be
relying on the end user to provide the proper delimiters that would
allow you to parse the steps properly.
I think this railscast might help you understand the basics of what you
need:
This continues in episode 74 as well.