Displaying Data from a CSV file on the web using a rails framework.

First I'm assuming that you have your standard rails folder stucture from the assignment: Move into the project directory:

cd rails

Now let's create a new controller for the csv handling

[jsantore@csdev01 rails]$ ruby script/generate controller csvdemo index

You should see output like the following:

exists app/controllers/
exists app/helpers/
create app/views/csvdemo
exists test/functional/
create app/controllers/csvdemo_controller.rb
create test/functional/csvdemo_controller_test.rb
create app/helpers/csvdemo_helper.rb
create app/views/csvdemo/index.rhtml

Next start the webserver:

ruby script/server -p 3200

I'm starting it on port 3200 to avoid collisions with any of you.

Now lets look at the controller, open it up in xemacs or another code aware editor:

xemacs app/controllers/csvdemo_controller.rb&

You should see the following code

Original csvdemo_controller.rb

class CsvdemoController < ApplicationController

  def index


so you need to add in the code for dealing with CSV files that we talked about in class.

New csvdemo_controller.rb

require 'csv'
class CsvdemoController < ApplicationController

  def index
    @file = 'demoData.csv'
    @table={"headings" => ["Name", "Category", "City", "Rating"],
      "body" => CSV::Reader.parse(File.open(@file))


You will also need to edit the view file:
xemacs app/views/csvdemo/index.rhtml&
This also has the scriptlet code and ruby expressions that we discussed in class.

New index.rhtml


    <% @table["headings"].each do |heading| %>
      <b><%= heading %></b>
    <%end %>

  <% @table["body"].each do |row| %>
      <% row.each do |col| %>
      <%= col %>
      <% end %>
  <% end %>


Finally you might be interested in the csv file that I was using to generate the file:


this, that, Akron, 1
Old Man, folks, Dallas, 2
Slice em and Dice em, odd stuff, Detroit, 4
Roast em and Toast em, odd stuff, Boston, 3
Mango Bob's asian bistro, eatery, Buffalo, 1

Make sure that you have demoData.csv in the root rails directory or that you update the file name in the controller to include the directory path that you are using.

you can find more information about the Ruby CSV handler in Dan's presentation or at