Main Content

Ruby of Rails - cleanly displaying model data in the view

Archive - Originally posted on "The Horse's Mouth" - 2012-06-23 11:35:06 - Graham Ellis

The display of data from our model has - thus far - been formatted in the Controller (when that really ought be in the view) and has been liable to fail to display properly if the data contains HTML special characters such as < and &. The solution to this is provided for you by rails - simply pass through the model object to be displayed to the view, and use the h method therein to "webify" the data.

1. Pass the complete object that you want to display through the controller into the view

  def single
    @main_result = "-"
    stockdata = Product.all
    stockdata.each do |stock|
      if stock.pname == params[:name] # Params is from a "form"
        @info = stock
      end
    end
  end


2. In the view, use the h function on individual member fields to ensure that they're cleaned on output

  <h1>Single Record Report</h1>
  To revert to product list: <b><%= @main_result %></b><br /><br />
  All about the product: <b><%= h @info.pname %></b><br />
    Price: <%= h @info.unitprice %><br />
    Quantity: <%= h @info.stocklevel %>
    <br /><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