Wednesday, August 27, 2008

Ruby Forms using select, textfields etc.

If you would like to connect form objects (textfields, selects etc.) to a field. You will want to wrap those fields in a form_for.

By using f.text_field and f.select you are don't have to worry about including the logic to populate your text_field (if the object exists) or select your option (if the object exists).

Note the select option. You usually create a select option by doing something like f.select (:school_level_id, [ ["First Years", 1] ["Second Years", 2] ]). The first parameter (:school_level_id) is a field in your model. The second parameter is a list of your options. Note that you can automatically create that list of lists using pretty ruby syntax like SchoolLevel.find(:all).collect { |c| [c.name, c.id] }).

If you want to set a default value:
# in controller which manages view described above
@work.project_id = params[:pid] unless params[:pid].nil?



For another brief summary like this, see here.

No comments: