Skip to content

Instantly share code, notes, and snippets.

@kamiller
Last active December 27, 2015 06:39
Show Gist options
  • Save kamiller/7283524 to your computer and use it in GitHub Desktop.
Save kamiller/7283524 to your computer and use it in GitHub Desktop.
Rails simple AR / Reporting example

For custom queries that require basically a whole custom SQL statement (your find above doesn't exactly abstract much from you) I like to set up a quick little new model that represents the new information. i.e.

class OperatingExpenseReportDatum
  attr_accessor :type, :heading, :total

  def initialize(row)
    # set values from row, like
    @total = row["total"].to_f
  end
end

and then write a helper method into the model, something like:

class Expense < AR::Base
  ...
  def self.operating_expenses
    rows = connection.select_all "SQL STATEMENT HERE"
    rows.map { |row| OperatingExpenseReportDatum.new(row) }
  end
end

Then your report generation is all nice:

#controller
@expenses = Expense.operating_expenses

view


<% @expenses.each do |expense| %>
  <%= expense.type %>: <%= expense.total %>
<% end %>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment