Search code examples
ruby-on-railsformsmathscaffolding

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


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

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

Thanks in advance!


Solution

  • In your view:

    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