0

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
  • One small thing first, when you create a new class, the word `class` needs to be lower case. So you will have `class Calculation < ApplicationRecord`. – davidhu Aug 30 '16 at 02:20
  • can you do something like `@calculation = addition(a, b)` – davidhu Aug 30 '16 at 02:20
  • @davidhu2000 re: spelling thanks, updated! re: addition - the function at present returns the calculated value (with no reference to the add variable). `@calculation` is referring to the calculation object as a whole, not a particular variable within the object.. I don't believe that will work –  Aug 30 '16 at 04:40

1 Answers1

0

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.

kobaltz
  • 6,980
  • 1
  • 35
  • 52
  • Awesome thanks @kobaltz - I was able to get this working using both `before_save` & `before_validation` callbacks, however I had to adjust the addition method to `self.add = a + b` This now raises the question - Why does the method only work if `self.` is appended to the variable? Shouldn't either work? –  Aug 30 '16 at 05:30
  • This [article](http://stackoverflow.com/questions/1693243/instance-variable-self-vs) explains things nicely. –  Aug 30 '16 at 05:32