Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to format values before saving to database in rails 3

I have a User model with Profit field. Profit field is a DECIMAL (11,0) type. I have a masked input on the form which allows user to input something like $1,000. I want to format that value and remove everything except numbers from it so i will have 1000 saved. Here is what i have so far:

class User < ActiveRecord::Base
  before_save :format_values

  private

  def format_values
    self.profit.to_s.delete!('^0-9') unless self.profit.nil?
  end
end

But it keeps saving 0 in database. Looks like it is converting it to decimal before my formatting function.

like image 438
Tamik Soziev Avatar asked Apr 18 '12 17:04

Tamik Soziev


People also ask

What does .save do in Ruby?

The purpose of this distinction is that with save! , you are able to catch errors in your controller using the standard ruby facilities for doing so, while save enables you to do the same using standard if-clauses.

What is ActiveRecord in rails?

What is ActiveRecord? ActiveRecord is an ORM. It's a layer of Ruby code that runs between your database and your logic code. When you need to make changes to the database, you'll write Ruby code, and then run "migrations" which makes the actual changes to the database.

What's the purpose of ActiveRecord?

Active Record facilitates the creation and use of business objects whose data requires persistent storage to a database. It is an implementation of the Active Record pattern which itself is a description of an Object Relational Mapping system.


1 Answers

Try this:

def profit=(new_profit)
  self[:profit] = new_profit.gsub(/[^0-9]/, '')
end
like image 92
jdoe Avatar answered Sep 28 '22 10:09

jdoe