Generating Forms for Manipulating Model Objects
Problem
You want to define actions that let a user create or edit objects stored in the database.
Solution
Lets create a simple model, and then build forms for it. Heres some MySQL code to create a table of key-value pairs:
use mywebapp_development; DROP TABLE IF EXISTS items; CREATE TABLE `items` ( id int(11) NOT NULL auto_increment, ame varchar(255) NOT NULL default \, value varchar(40) NOT NULL default [empty], PRIMARY KEY (id) );
Now, from the command line, create the model class, along with a controller and views:
$ ./script/generate model Item exists app/models/ exists test/unit/ exists test/fixtures/ create app/models/item.rb create test/unit/item_test.rb create test/fixtures/items.yml create db/migrate create db/migrate/001_create_items.rb $ ./script/generate controller items new create edit exists app/controllers/ exists app/helpers/ create app/views/items exists test/functional/ create app/controllers/items_controller.rb create test/functional/items_controller_test.rb create app/helpers/items_helper.rb create app/views/items/new.rhtml create app/views/items/edit.rhtml
The first step is to customize a view. Lets start with app/views/items/new.rhtml. Edit it to look like this:
<%= form_tag :action => "create" %> Name: <%= text_field "item", "name" %>
Value: <%= text_field "item", "value" %>
<%= submit_tag %> <%= end_form_tag %>
All these method calls generate HTML: form_tag opens a