Cover by Leonard Richardson, Lucas Carlson

Safari, the world’s most comprehensive technology and business learning platform.

Find the exact information you need to solve a problem on the fly, or go deeper to master the technologies and skills you need to succeed

Start Free Trial

No credit card required

O'Reilly logo

15.16. 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

Let's create a simple model, and then build forms for it. Here's 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,
	  'name' 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. Let's start with app/views/items/new.rhtml. Edit it to look like this:

	<!-- app/views/items/new.rhtml -->
	 
	<%= form_tag :action => "create" %>
	 Name: <%= text_field "item", "name" %><br />
	 Value: <%= text_field "item", "value" %><br />
	 <%= submit_tag %>
	<%= end_form_tag %>

All these method calls generate HTML: ...

Find the exact information you need to solve a problem on the fly, or go deeper to master the technologies and skills you need to succeed

Start Free Trial

No credit card required