Computed Columns?

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

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


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?



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.