Clean up string data before saving in database as integer
I have an integer column called dollars
in my database table and I am attempting to save values such as $1000
in the database. However, attempting to save the string $1000
with the dollar sign in an integer column will cause an automatic conversion to the integer 0
.
To prevent this from happening, I tried to add a before_save
callback to my clean_data
method in my model to remove the dollar sign. But it seems that rails has already attempted to save the entire $1000
string in the database before clean_data
is called.
I wonder if there is a better way to remove the dollar sign from the values before saving to the database as an integer?
Here's my code:
In the create
action of the bids_controller.rb
, doing this will allow the database to save the value $1000
from the form properly:
# Remove dollar sign
if params[:bid][:dol开发者_高级运维lars][0] == "$"
params[:bid][:dollars] = params[:bid][:dollars].delete('$')
end
@bid = Bid.new(params[:bid])
@bid.save
However, if I were to remove the if-end fragment from the controller and clean the data in the Bid
model, like this:
before_save :clean_data
def clean_data
puts self.dollars
self.dollars = self.dollars.delete('$')
end
I will get the value 0
for puts self.dollars
before the clean_data
method has a chance to remove the dollar sign.
My hypothesis is that rails has attempted to "hold" the data in the database before either clean_data
or save
is called, and this "hold" causes the data to be converted to 0
since the integer column isn't able to save the dollar sign.
Thank you very much for your help! :)
Take a look at the tr
method.
"$1000".tr("$", "") # => "1000"
You should be able to do this on the string variable prior to saving it to the database.
精彩评论