简体   繁体   中英

Rails convert integer value before save

I have an database with an enginze size for the car Therefore user can write something like 2.5 (like in liters) or 2500 (cc) Later on I have an sorting and it should using 999-9999 values to compare

I came up the function below, but I would like it be more flexible. Moreover, 2.5 causing the result of 2000 now because looks like Rails converting value before triggering before_save

How do I make convert right and detect if there is an point or comma in input?

before_save :covert_engine

private
def covert_engine
    if self.car_engine_size.present?
        if Math.log10(self.car_engine_size).to_i + 1 < 4
            self.car_engine_size = self.car_engine_size * 1000
        end
    end
end

PS self.car_engine_size is an integer in database

If you want the user to be able to use different units of input I would make it explicit to the user by letting them select the unit.

Start by creating a virtual attribute

class Car
  attr_accessor :engine_size_unit
end

Add the attribute to the form and whitelist it in the controller

<%= f.number_field :engine_size %>
<%= f.select :engine_size_unit, ['cc', 'l']) %>

Then convert the value in the model using the value before the typecast

class Car
  before_save :covert_engine, 
    if: -> { car_engine_size.present? && engine_size_unit == 'l' }

  def covert_engine
    converted = car_engine_size_before_type_cast * 1000
    self[:car_engine_size] = converted.to_i
  end
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM