Forum: Ruby on Rails calculations on a virtual attribute...

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
holden (Guest)
on 2009-05-03 13:25
(Received via mailing list)
I is possible to do calculations on a virtual attribute... such as
sum, or count

I tried using the same as I would on a DB column but of course that
doesn't work. ie.  Pricelist.sum(:cyberguide)

I have a table with 2 fields, one with a price and the other with a
condition then have a virtual attribute which does a calculation:

  def cyberguide
    if condition <= 2
      [price.pricehigh]
    elsif condition == 3
      [price.pricehigh * 0.9]
    elsif condition == 4
      [price.pricehigh * 0.5]
    elsif condition == 5
      [price.pricehigh * 0.25]
    elsif condition == 6
      [price.pricehigh * 0.2]
    else
      [price.pricehigh * 0.15]
    end
  end

It works perfectly for individual functions, but how would a sum the
virtual attribute?

Thanks
Frederick C. (Guest)
on 2009-05-03 13:35
(Received via mailing list)
On May 3, 7:55 am, holden <removed_email_address@domain.invalid> wrote:
> I is possible to do calculations on a virtual attribute... such as
> sum, or count
>
> I tried using the same as I would on a DB column but of course that
> doesn't work. ie.  Pricelist.sum(:cyberguide)
>
You're going to have to construct an appropriate sql fragment, eg
according to the docs you can do Pricelist.sum("2 * price") - you just
need that on steroids.


Fred
This topic is locked and can not be replied to.