How to properly use before_save?

Hello everyone!!

I’m encountering an issue with before_save and the data type in the database. Specifically, I have a column in my database defined as type integer (t.integer :examplenumber). In my model, I retrieve the value of this parameter:

class User < ApplicationRecord
  before_create :example

  private

  def example

    puts "Param value: #{examplenumber}"

  end
end

The problem arises because, being an integer type in the database, it doesn’t allow decimals, only integers. While this is logical, my intention is to handle decimals before saving them, for various reasons. I want to convert decimals to integers before saving them. How can I achieve this?

For instance, if a user inputs 1.50, currently, it prints Param value: 1. However, if I change the database type to something else that allows decimals, it does print Param value: 1.50. How can I ensure it prints the decimal even though the type in the database is integer?

Note: I need to save integers, not decimals, in the database.

Thank you all for your help.

Why do you want to print the decimal?

You could try overwriting the setter if you want to handle the rounding yourself instead of letting ActiveRecord do it for you.

1 Like

Hi Gabe Odess, thank you very much for your time, it worked for me.

:pray:

Have a good day!