Providing a form to allow the user to add data to the model - Ruby on Rails
Archive - Originally posted on "The Horse's Mouth" - 2012-06-23 11:19:21 - Graham EllisSo far, we have implemented a single model - view - controller application using Ruby on Rails, and displayed the data in several forms. How do we add new data? We need to provide an "add product" form, and code to handle that form when it's submitted. Building on the example so far, here's how:
Adding in a form for "add product"
1. Add a link (to index.erb?) for add product:
To add a product - go <a href=addproduct>[here]<
2. Add an "addproduct" method to the controller
def addproduct
@main_result = "This is where we add a product - initial form"
@newprod = Product.new
@info = ""
end
3. Add the view for that form (app/views/productlister/addproduct.erb )
<h1>All records report</h1>
Here is a message: <b><%= @main_result %></b><br /><br />
Here is the "add product" form to fill in:<br />
<% form_for(@newprod, :url => "/productlister/saveproduct") do |fieldname| %>
Name of product <%= fieldname.text_field :pname %><br />
Price Each <%= fieldname.text_field :unitprice %><br />
Initial Stock Held <%= fieldname.text_field :stocklevel %><br />
<%= fieldname.submit "Done!" %><br />
<% end %><br />
4. Add a saveproduct method to the controller
def saveproduct
@main_result = "Saving a new product"
@newprod = Product.new(params[:product])
if @newprod.save
redirect_to :action => "index"
else
redirect_to :action => "addproduct" # error handling - next article
end
end
(no need to provide a template because it sends it back to the index)
5. Try it!
This is one of a series of summaries taking you from initial installation of Ruby and Rails through to a complete multitable application: [link] - Installing Ruby and Rails [link] - Hello World, Ruby on Rails Style [link] - What and Why - Model, View, Controller [link] - Multiple views, same model [link] - A form to allow data to be added to the model [link] - Validating data entries for storage in the model [link] - Cleanly viewing model data [link] - Complete sample, including a multiple table model These topics are covered on our Introduction to Rails day - an optional extension of Ruby Programming or Learning to program in Ruby |