# Computed Columns?

**URL:** <https://www.ruby-forum.com/t/computed-columns/121673>\
**Category:** Rails\
**Created:** [November 29, 2007, 8:39pm UTC](https://www.ruby-forum.com/t/computed-columns/121673 "2007-11-29T20:39:28Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![ryan](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/r/a8b319/32.png) [@ryan](https://www.ruby-forum.com/u/ryan)\
**Post date:** [November 29, 2007, 8:39pm UTC](https://www.ruby-forum.com/t/computed-columns/121673/1 "2007-11-29T20:39:28Z")

</div>

Time to stretch.

I want to acheive a find that returns a computed value as a column. I  
don’t know SQL (thanks to Rails hiding me from it up until now) and I  
don’t know if Rails will be able to help. Here’s my model.

class Trackable \< ActiveRecord::Base  
has\_many :time\_entries, :dependent =\> :destroy  
has\_many :time\_chargers, :through =\> :time\_entries, :source  
=\> :owner, :uniq =\> true  
end

# Of course I can do:

trackables = Trackable.find(:all)

# Now assume that trackables[0].time\_chargers

# would return 3 people: Fred Flinstone, Wilma Flinstone, Barny

Rubble

# I can then get how many time\_chargers there are by doing:

trackables[0].time\_chargers.size # =\> 3

# I want that value computed by the original SQL query returned from

find, so additional queries aren’t created.

# Further I want to be able to do the same search with conditions

added to time\_chargers at the time of the find.

# Something like:

trackables = Trackable.find :all, with\_scope =\>  
“time\_chargers.last\_name == Flinstone”

# So now I get:

trackables[0].time\_chargers.size # =\> 2

# again without an additional SQL query.

I suppose if I have to dive down to SQL that’s ok, but mixing Rails  
generated SQL and hand crafted SQL feels so wrong. That’s and I don’t  
really know SQL. Where should I begin?

Ryan

---

<div class="post-metadata">

**Author:** ![ryan](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/r/a8b319/32.png) [@ryan](https://www.ruby-forum.com/u/ryan)\
**Post date:** [November 30, 2007, 10:14am UTC](https://www.ruby-forum.com/t/computed-columns/121673/2 "2007-11-30T10:14:27Z")

</div>

Hi,

if your tables are not really huge I think you can just add  
an :include option to your first find(:all) for your associations…  
which means that rails will load table data for the assocations as  
well in that one query.

–  
Volker
