James James - 1 year ago 39
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
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
object params in the controller.

class Calculation < ApplicationRecord
def addition(a, b)
return a + b

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 ...
... render :new ...

Answer Source

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
  render :new

So within your model,

class Calculation < ApplicationRecord
  before_save :addition


  def addition
    add = a + b

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.