Rails Convert Percentage Value on Edit Form

2019-07-29 07:35发布

问题:

I have the following callback and method in my Customer model.

before_save :convert_commission_percentage

def convert_commission_percentage
  self.commission= commission.to_f/100.to_f
end

This allows the user to input a percentage as 45 and store it as .45. However, on edit, the field for this percentage is then displayed as .45 on the edit form, causing that number to be divided by 100 again on update. Is there a way to keep this from happening by displaying the edit field as 45?

回答1:

There are a few options:

  1. Why store converted value, why not store whatever the user inputs without modification. commission_percentage might be a better name. You could create an alias commission to commission_percentage with alias_attribute :commission, :commission_percentage if you'd like to use commission attribute instead of commission_percentage attribute in your application.

  2. Using after_initialize callback:

    before_save :convert_commission_percentage
    
    after_initialize do 
      commission = commission.to_f * 100
    end
    
    def convert_commission_percentage
      self.commission= commission.to_f/100.to_f
    end
    
  3. Through getters and setters:

    def commission=(value)
      write_attribute :commission, value.to_f/100
    end
    
    def commision
      read_attribute(:commission).to_f * 100
    end