Reputation: 897
I need to get the values from a form and adjust it before the form updates.
What I have is a Project and a project has many Main Groups and Main Groups has many Trades.
So before I save a form, I want to check if there are any values for the cost input in Trades and if there are, the sum of this should overwrite the cost value for Main Groups.
So here is what I have:
class MainGroup < ActiveRecord::Base
belongs_to :project
has_many :trades
accepts_nested_attributes_for :trades, :reject_if => :all_blank, :allow_destroy => true
private
before_update do
if (self.trades.sum(:cost) != 0)
self.cost = self.trades.sum(:cost)
else
self.cost = self.cost
end
end
end
The only problem is that it uses the current values in the DB instead of the new ones in the form.
Thanks.
Upvotes: 0
Views: 76
Reputation: 960
before_save :update_cost_from_trades
private
def update_cost_from_trades
unless trades.sum(:cost).is_zero?
self.cost = trades.sum(:cost)
end
end
Upvotes: 1