Generating Forms with Ruby on Rails

Rails forms start with generating model for the form. Let’s start by generating Item model that will have corresponding form for its fields.

rails generate model Item name value
rake db:migrate
rails generate controller items new create edit

Three rails commands, listed above, will generate all necessary files for to start constructing Ruby form. In order for us to start a form, we need to find new.html.erb file and modify html in it.

<%=form_tag :action=>”create” do -%>
 Name: <%= text_field “item”, “name”%>
 Value: <%=text_field “item”, “value”%>
<%=submit_tag%>
<%=end-%>

Please not that text field <%=text_field “item”, “value”%> is created with “item” and “value” in it. Rails framework uses both of these values in order to bind text field to the instance variable called @item and “value” member of @item.

This @item variable is set in the controller.

class ItemsController < ApplicationController
 def new
  @item = Item.new
 end

 def create
  @item = Item.create(params[:item])
   redirect_to :action => ‘edit’, :id=>@item.id
 end

 def edit
  @item = Item.find(params[:id])
  if request.post?
   @item.update_attirbutes(params[:item])
   redirect_do: action => edit, :id => @item_id
  end
 end
end

The ItemsController class set @item to null and assigns new value to text fields in our create form to empty values. On the same form, we have submit button that call on create action of the ItemsController class. In turn, create action calls on edit action after item is persisted to the model. We also have edit.html.erb file that will be loaded upon a call to edit action.

Featured pages

Ruby

Set of Ruby Object Oriented Programming Language tutorials that cover such topics as Ruby strings, …

Rails

Rails Framework tutorial teaches you how to utilize de facto framework of choice for Ruby developme…

Ruby Duck Typing

“If an object quacks like a duck just go ahead and treat it as a duck” – this fun…

Regular Expressions

Ruby uses the =~ operator to check any given string against regular expression. For example, a stri…

Credit Card Number

Every last digit of any credit card is a check sum digit that is determined by all digits in front …

Ruby Arrays

Ruby Programming Language has built in support for Arrays. Arrays help you define some of the compl…

Ruby Hashes

Hashes are very similar to arrays in Ruby and hashes interface is similar to Ruby array interface. …

Ruby Code Block

Ruby is very unique language when it comes to code blocks. You can simply pass a code block to a me…