Calculate methods on attr_accessor objects

Is it possible to use the calculate methods (sum, etc.) on attr_accessor
attributes?

Ie:

Class Item < ActiveRecord::Base
attr_accessor :total_cost

def total_cost
@total_cost = self.cost_unit * self.amount
end

calling Item.sum(:total_cost) or Item.sum(‘total_cost’) both return a
unknown column ‘total_cost’ mysql error.

I thought that active record considers attr_accessor objects the same as
columns in the table and all methods available to the model class would
be
available to the attr_accessor too. Is that not so?

On Thursday, July 27, 2006, at 11:02 AM, zer0halo wrote:

end
“Impossible is nothing.”


Rails mailing list
[email protected]
http://lists.rubyonrails.org/mailman/listinfo/rails

IIRC the AR Calculations feature actually lets the DB do the
calculation, so it needs to understand how to do the calculation before
it will work.

Something like this may work…

Item.sum(:select=>’(cost_unit + amount)’)

Not tested, so YMMV.

_Kevin
www.sciwerks.com

Thanks, Kevin. That didn’t work, but it got me going in the right
direction.

Through a bit of trial and error I discovered that contrary to what the
AR rdoc says, count_by_sql accepts other methods than just COUNT.

So this works:

Item.count_by_sql(“select sum(cost_unit * amount) from items”)

Not very “rails like” though :-(. I should probably write a
calculate_by_sql helper that accepts all the various calculate commands
for those instances where you need more than just the sum of a single
column or where that column doesn’t exist.

Kevin O. wrote:

Something like this may work…

Item.sum(:select=>’(cost_unit + amount)’)

Item.count_by_sql(“select sum(cost_unit * amount) from items”)

Item.sum ‘cost_unit * amount’

Ah of course, I figured there was a simple Rails way but hadn’t found
it. Why didn’t I try that? :slight_smile:

The kind of thing that would be handy to add to the documentation.

By the way, there used to be annotated documentation at
rails.outertrack.com but it’s down these days. Has it moved elsewhere? I
could add a comment on this to it.

Rick O. wrote:

Item.count_by_sql(“select sum(cost_unit * amount) from items”)

Item.sum ‘cost_unit * amount’

On Thursday, July 27, 2006, at 9:41 PM, François Montel
wrote:

Item.count_by_sql(“select sum(cost_unit * amount) from items”)

Item.sum ‘cost_unit * amount’


Posted via http://www.ruby-forum.com/.


Rails mailing list
[email protected]
http://lists.rubyonrails.org/mailman/listinfo/rails

http://railsmanual.org

_Kevin
www.sciwerks.com

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs