# Active Record SQL View Support for SQL Server - Is this supported/possible?

**URL:** <https://discuss.rubyonrails.org/t/active-record-sql-view-support-for-sql-server-is-this-supported-possible/10697>\
**Category:** rubyonrails-talk\
**Created:** [March 23, 2007, 6:11pm UTC](https://discuss.rubyonrails.org/t/active-record-sql-view-support-for-sql-server-is-this-supported-possible/10697 "2007-03-23T18:11:50Z")\
**Posts on this page:** 7\
**Page:** 1

<div class="post-metadata">

**Author:** ![BrendanC](https://avatars.discourse-cdn.com/v4/letter/b/e9c0ed/32.png) [@BrendanC](https://discuss.rubyonrails.org/u/BrendanC)\
**Post date:** [March 23, 2007, 6:11pm UTC](https://discuss.rubyonrails.org/t/active-record-sql-view-support-for-sql-server-is-this-supported-possible/10697/1 "2007-03-23T18:11:50Z")

</div>

I'm just exploring ROR for the first time - so excuse me if that has already been asked/answered. I'm intersted in developing a Web front end to an existing SQL Server database - migrating this to MySql/ Postgres is NOT an option.

The front end needs to display data that is aggregated from multiple tables via SQL server views. The views already exist in the database and are sufficiently complex that I cannot consider recoding them using business objects etc.

Is it possible to use a SQL Server view as the source for an Active Record - I want to create a form that displays the aggregrated data (represented by views). There in no requirement to update from these views.

Any links/references/examples/tutorials would be helpful.

TIA, BrendanC

---

<div class="post-metadata">

**Author:** ![Tom\_Ward](https://avatars.discourse-cdn.com/v4/letter/t/54ee81/32.png) [@Tom\_Ward](https://discuss.rubyonrails.org/u/Tom_Ward)\
**Post date:** [March 23, 2007, 6:33pm UTC](https://discuss.rubyonrails.org/t/active-record-sql-view-support-for-sql-server-is-this-supported-possible/10697/2 "2007-03-23T18:33:08Z")

</div>

I do this all the time without any problems. Simply access the view as though it were a table.

Tom

---

<div class="post-metadata">

**Author:** ![Ball\_Donald\_A\_Jr\_Lib](https://avatars.discourse-cdn.com/v4/letter/b/f475e1/32.png) [@Ball\_Donald\_A\_Jr\_Lib](https://discuss.rubyonrails.org/u/Ball_Donald_A_Jr_Lib)\
**Post date:** [March 23, 2007, 7:42pm UTC](https://discuss.rubyonrails.org/t/active-record-sql-view-support-for-sql-server-is-this-supported-possible/10697/3 "2007-03-23T19:42:40Z")

</div>

> I do this all the time without any problems. Simply access the view as though it were a table.

I do this for aggregate statistics views by choosing the model most closely tied to the view and calling find\_by\_sql on its class. Is there a benefit to actually making model objects for the views? How do you cope with views that do not have primary keys? Alternately, is there a benefit to getting the DBI connection and calling query manually instead of going through find\_by\_sql?

- donald

---

<div class="post-metadata">

**Author:** ![Tom\_Ward](https://avatars.discourse-cdn.com/v4/letter/t/54ee81/32.png) [@Tom\_Ward](https://discuss.rubyonrails.org/u/Tom_Ward)\
**Post date:** [March 26, 2007, 8:12am UTC](https://discuss.rubyonrails.org/t/active-record-sql-view-support-for-sql-server-is-this-supported-possible/10697/4 "2007-03-26T08:12:21Z")

</div>

As long as you're not doing updates, the lack of primary keys isn't an issue. Using a model object gives the adapter the opportunity to type cast the returned values consistently. It also makes it easier to auto-generate aggregate queries (avoiding find\_by\_sql). As an example, I use a plugin that allows SalaryReport.group\_by(:department\_id) and similar. I can share if you're interested.

Tom

---

<div class="post-metadata">

**Author:** ![Tom\_Ward](https://avatars.discourse-cdn.com/v4/letter/t/54ee81/32.png) [@Tom\_Ward](https://discuss.rubyonrails.org/u/Tom_Ward)\
**Post date:** [March 26, 2007, 12:27pm UTC](https://discuss.rubyonrails.org/t/active-record-sql-view-support-for-sql-server-is-this-supported-possible/10697/5 "2007-03-26T12:27:57Z")

</div>

I'm not able to officially release it as I don't have the time to support it. I can provide the (very scrappy) code if you want to play around with it, at your own risk! Usage is pretty basic. First, define model with some aggregates:

class SalaryReport \< ActiveRecord::Base &nbsp;&nbsp;self.aggregates = { &nbsp;&nbsp;&nbsp;&nbsp;:salary =\> 'sum(salary)', &nbsp;&nbsp;&nbsp;&nbsp;:average\_salary =\> 'avg(salary)' &nbsp;&nbsp;} end

Then, call group\_by(columns) to get something you can turn into a report:

SalaryReport.group\_by(:country\_id, :department\_id)

It will select all the aggregated columns you've defined, as well as the grouped attributes, so the example above is similar to

SELECT country\_id, department\_id, sum(salary) salary. avg(salary) average\_salary FROM salary\_report GROUP BY country\_id, department\_id

You can also include conditions if you wish, similar to those for the find method:

SalaryReport.group\_by(:country\_id, :conditions =\> {:region\_id =\> 'EUROPE'})

Here's the actual code:

module Tomafro::ActiveRecord::GroupBy &nbsp;&nbsp;def self.included(base) &nbsp;&nbsp;&nbsp;&nbsp;base.extend(ClassMethods) &nbsp;&nbsp;end

&nbsp;&nbsp;module ClassMethods &nbsp;&nbsp;&nbsp;&nbsp;def group\_by(\*groups) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;groups = groups.dup.flatten &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;options = groups.last.is\_a?(Hash) ? groups.pop : {} &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;scope = scope(:find) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;aggregate\_columns = self.aggregates.collect do |key, value| &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"#{value} #{key}" &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;end &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;group\_columns = groups.collect(&:to\_s) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;sql = "SELECT #{(group\_columns + aggregate\_columns).join(",\n ")} " &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;sql \<\< "FROM #{table\_name} " &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;add\_conditions!(sql, options[:conditions], scope) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;sql \<\< " GROUP BY #{group\_columns.join(", ")}" &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;sql \<\< " WITH ROLLUP" if options[:rollup] &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;records = find\_by\_sql(sql) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;records.each { |record| record.readonly! } &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;records &nbsp;&nbsp;&nbsp;&nbsp;end

&nbsp;&nbsp;&nbsp;&nbsp;def aggregates &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;@aggregates || {} &nbsp;&nbsp;&nbsp;&nbsp;end

&nbsp;&nbsp;&nbsp;&nbsp;def aggregates=(aggregates) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;@aggregates = aggregates &nbsp;&nbsp;&nbsp;&nbsp;end &nbsp;&nbsp;end end

ActiveRecord::Base.send(:include, Tomafro::ActiveRecord::GroupBy)

---

<div class="post-metadata">

**Author:** ![Craig\_Demyanovich](https://avatars.discourse-cdn.com/v4/letter/c/e47c2d/32.png) [@Craig\_Demyanovich](https://discuss.rubyonrails.org/u/Craig_Demyanovich)\
**Post date:** [March 26, 2007, 2:03pm UTC](https://discuss.rubyonrails.org/t/active-record-sql-view-support-for-sql-server-is-this-supported-possible/10697/6 "2007-03-26T14:03:48Z")

</div>

I just read about ActiveRecord::Calculations::ClassMethods this morning. Tom, do the grouping capabilities provided by those methods not meet your needs such that you wrote this plugin for yourself?

Thanks, Craig

---

<div class="post-metadata">

**Author:** ![Tom\_Ward](https://avatars.discourse-cdn.com/v4/letter/t/54ee81/32.png) [@Tom\_Ward](https://discuss.rubyonrails.org/u/Tom_Ward)\
**Post date:** [March 26, 2007, 2:26pm UTC](https://discuss.rubyonrails.org/t/active-record-sql-view-support-for-sql-server-is-this-supported-possible/10697/7 "2007-03-26T14:26:57Z")

</div>

> I just read about ActiveRecord::Calculations::ClassMethods this morning. Tom, do the grouping capabilities provided by those methods not meet your needs such that you wrote this plugin for yourself?

Last I looked, the Calculations stuff could only pull out a single aggregate at a time. i.e to find total payroll and average salary would take two queries:

SalaryReport.sum(:salary, :conditions =\> {:country\_id =\> 'DE'}) SalaryReport.avg(:salary, :conditions =\> {:country\_id =\> 'DE'})

Of course, it's also possible to get these results using the standard finder:

SalaryReport.find(:all, :select =\> 'sum(salary) total\_salary, avg(salary) avg\_salary' .......)

I'm not advocating my code over either of these techniques. For my particular purpose, where I'm pulling several reports down from views, each of which can be grouped in an astounding number of ways, my little piece of code has proved useful. For general grouping code, you may well find the existing finder methods sufficient.

Tom
