Thursday, August 8, 2013

Making Report Views in Ruby on Rails

I am in the middle of launching another Ruby on Rails web application that was left to me to finish. I've spent several months adding features, fixing the data models, cleaning up styles and UI. Pretty much maintenance tasks and support but without the main architect or developer. The remaining major issues left for me was to import 8 years of data and develop some reporting functions. I will probably write about the data export/import experience later. However, creating reports was a fairly complicated effort due to not a lot of explicit help or examples.

When I talk about reporting, I am referring to data models that bring together lots of tables worth of data and then allow the viewer to select, sort and filter on their own. In our shrinking and harried unit it is becoming clear that web apps are not the best place to manage data sets of any significance. Security issues, application responsiveness and development speed are all significant obstacles for us. Only ease of deployment and flexibility of access work in a web app's favor. And for in-house, departmental apps that may not be enough of an advantage.

Regardless, this app needs reports!

So, first I create the Views I need in SQL Server. No problem, I do that all the time, but how do I call them in Rails? Stack Overflow has a start for me. And I create a model to call the View I built.

rails generate model report_gme_by_opening

I throw away the migration that is generated and paste in the example.

class ReportGmeByOpening < ActiveRecord::Base
  # attr_accessible :title, :body
  set_table_name "report_gme_by_opening"
  #set_primary_key "if_not_id"
end


I don't need the primary key (there is none) and I don't think I need any accessible attrs since it is read only.

Wait, I need a reports controller in my admin part of the app if this is going to work.

rails generate controller admin/reports gme_by_opening

This gives me a blank controller and a definition of one report controller.

class Admin::ReportsController < Admin::AdminController
  respond_to :html
 
  def gme_by_opening
    @results = ReportGmeByOpening
    @results_count = @results.count
    respond_to do |format|
      format.html # gme_by_opening.html.erb
    end
  end
end


And then I make a gme_by_opening.html.erb file with some basic info.

<h1>GME Department Coverage by Site Openings</h1>
<p><%= @results_count %> records returned.</p>


And then I need to make a route available.

namespace :admin do
  match '/reports/gme_by_opening', :to => 'reports#gme_by_opening'
end


Finally I can make a link like this.

<%= link_to "GME by Openings", admin_reports_gme_by_opening_path%>

All the pieces work and I can get to my page and have some basic output. But next I need some filtering and grouping to make this useful to my customers.

No comments:

Post a Comment