Adding validation to form entries and sticky fields - Ruby on Rails
Archive - Originally posted on "The Horse's Mouth" - 2012-06-23 11:27:20 - Graham EllisSo far, we have implemented an MVC application under Ruby in Rails, and provided a rudimentary form to allow the user to add rows to the model. In this section, we show you the extra code needed to validate the data, and to echo it back out to the user within the form if it's incorrect.
1. In the model, add some calls to provide criteria against which to validate
class Product < ActiveRecord::Base
validates_presence_of :pname, :unitprice, :stocklevel
validates_numericality_of :unitprice, :stocklevel
validates_uniqueness_of :pname
end
2. In the controller, add code to see if the save of the new record worked
def saveproduct
@newprod = Product.new(params[:product])
if @newprod.save # And checks the object
redirect_to :action => "index" # to method (above)
else
@main_result = "Please correct"
render :action => "addproduct" # using view
end
end
3. Add the error messages to the view:
<% form_for(@newprod, :url => "/productlister/saveproduct") do |fieldname| %>
<%= fieldname.error_messages %>
<%= fieldname.label :pname %>
Name of product <%= fieldname.text_field :pname %><br />
<%= fieldname.label :unitprice %>
Price Each <%= fieldname.text_field :unitprice %><br />
<%= fieldname.label :stocklevel %>
Initial Stock Held <%= fieldname.text_field :stocklevel %><br />
<%= fieldname.submit "Done!" %><br />
<% end %><br />
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 |