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.