James James - 3 months ago 7
Ruby Question

Rails 5 - Calculate an object variable, based on two other variables

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

Answer

So within your controller, you may have something like this

# params => { a: 1.0, b: 2.0 }

@calculation = Calculation.new(params)
if @calculation.save
  redirect_to @calculation
else
  render :new
end

So within your model,

class Calculation < ApplicationRecord
  before_save :addition

  private

  def addition
    add = a + b
  end
end

However, if you are validating the presence of a, b, and add then you can use the before_validation callback instead to set the value of add.

Check out http://api.rubyonrails.org/classes/ActiveRecord/Callbacks.html for the list and order of the ActiveRecord callbacks.

Comments