How to calculate the difference of two fields in a Ruby on Rails submit form

I am new to Ruby on Rails and have used Scaffolding. On one of the forms, I want to have two fields and then have the difference between the two submitted to the database.

Instead of: pickupamount, I want (Ending Amount - Start Amount) to be calculated and entered into the pickupamount column of my database.

Thanks in advance!

+2


source to share


2 answers


In your opinion:

form_tag '/some_action' do
    text_field_tag 'start_amount'
    text_field_tag 'end_amount'
end

      



In your controller:

def create
    model = Model.new
    model.pickupamount = params[:end_amount].to_i - params[:start_amount].to_i
    model.save!
end

      

0


source


You can do this either in your model or in your controller. Following the Skinny Controller Fat Model , it might be better to add functionality to your model. Check out ActiveRecord callbacks .

class MyModel < ActiveRecord::Base
  attr_accessor :start_amount, :end_amount
  before_create :calculate_pickup_amount

  private
    def calculate_pickup_amount
      self.pickupamount = end_amount.to_i - start_amount.to_i
    end
end

      

Then in your controller:

def create
  # Assuming params[:my_model] has all the data for initializing a MyModel,
  # including start_amount and end_amount but not pickupamount:
  my_model = MyModel.new(params[:my_model])

  if my_model.save
    # Yay, do something
  else
    # Fail, do something else
  end
end

      



It might be helpful to include the following extension class in your Ruby class String

(thanks to sikelianos ), perhaps in a file in your Rails app directory:

class String
  def numeric?
    Float self rescue false
  end
end

      

Then you can check before installing pickupamount

:

def calculate_pickup_amount
  if end_amount.numeric? && start_amount.numeric?
    self.pickupamount = end_amount.to_i - start_amount.to_i
  else
    # Throw exception, set some default value, etc.
  end
end

      

+2


source







All Articles