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 System
class, 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
)
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.