Let's say I have a calculation model in Rails 5 with 3 variables:
a - float
b - float
add - float
Only two variables are present (a & b) in the calculation view when creating the object.
I want to call the addition(a, b)
function from the controller, which calculates the "add" variable before the object is saved to the database.
How can I use this function (or similar) in the calculations_controller.rb
to calculate and store the result in the database? This should also be called whenever the object is updated.
Current thinking: The function should be called in both the create and update functions in the controller. Or possibly using a before_save callback. I'm a little stumped however, on how to assign the result of the function to the @calculation
object params in the controller.
class Calculation < ApplicationRecord
def addition(a, b)
return a + b
end
end
An example Controller:
class CalculationsController < ApplicationController
def create
# calculate and assign to :add variable here?
@calculation = Calculation.new(calculation_params)
respond_to do |format|
if @calculation.save
... redirect_to ...
else
... render :new ...
end
end
end