Search code examples
ruby-on-railsrubyclasssumattr

linked attributes between classes (ruby on rails)


Good morning, I'm having an issue in my rails app when trying to link attributes between two classes. Let me explain better:

I have a Systemclass, which belongs_to my Area class (one area has_many systems). Both of them have an attribute called price. The price of an area must be the sum of the prices of all the systems it has.

Is there any way to make this relation without having to update the area's price every time I change one of it system's price? (I do something like @system.area.price = @system.area.price + @system.price)


Solution

  • If you're ok with handling this in the database, the sum calculation will do it for you: http://api.rubyonrails.org/classes/ActiveRecord/Calculations.html

    class Area < ActiveRecord::Base
      has_many :systems
      def price
        systems.sum('price')
      end
    end
    

    You could remove the Area's price field altogether.