Clint Chancellor
Clint Chancellor

Reputation: 1

Rails - Edit View - Can't save to MySQL:decimal using number_to_currency helper

I have 2 database columns (using mysql) one a decimal(10,2) the other a string.

Migration looks like.

t.decimal :PRICE, precision: 10, scale: 2
t.string :TOTALTAX

In a _form.html.erb partial, I have the following using the number_to_currency helper.

<div class="form-group">
    <%= f.label :PRICE %>
    <br>
    <%= f.text_field :PRICE, :value => number_to_currency(f.object.PRICE, :precision => 2), :class=>'form-control' %>
</div>
<div class="form-group">
    <%= f.label :TOTALTAX %>
    <br>
    <%= f.text_field :TOTALTAX, :value => number_to_currency(f.object.TOTALTAX, :precision => 2), :class=>'form-control' %>
</div>

Starting off I have "3429.65" in the TOTALTAX string, and "189900.00" in the decimal.

When I use the partial in the edit view. Everything renders as you would expect and my numbers. in theirs fields, look all pretty, which is what I want. Easy to read.

However, when I submit the form to Edit (update), my string saves to the db as "$3,429.65" which is okay, but my decimal saves as "0.00". What happened to my data?

Secondly, if I go back and re-enter the edit view my decimal (PRICE) obviously displays as "$0.00" but now my string (TOTALTAX) displays at "$$3,429.65". It just keeps prepending $ signs every time I re-enter the view and update.

Thoughts???

I tried using a before_save hook in the model with no success, that code looks like.

before_save :strip_currency
def strip_currency
   self.PRICE = self.PRICE.to_s.gsub(/[$,]/,"").to_d
   self.TOTALTAX = self.TOTALTAX.to_s.gsub(/[$,]/,"")
end

Upvotes: 0

Views: 221

Answers (1)

Clint Chancellor
Clint Chancellor

Reputation: 1

I HATE doing this way, but it works. I am still open to other solutions.

In the controller, I hijacked the params, stripped out any $ and , signs and sent my hacked params hash to the .update method.

def update
  respond_to do |format|
    removecurrency = deals_params
    removecurrency['PRICE'] = removecurrency['PRICE'].to_s.gsub(/[$,]/,"")
    removecurrency['TOTALTAX'] = removecurrency['TOTALTAX'].to_s.gsub(/[$,]/,"")
    removecurrency['SAFECOMP'] = removecurrency['SAFECOMP'].to_s.gsub(/[$,]/,"")
    if @deals.update(removecurrency)
      format.html { redirect_to @deals, notice: 'Deal was successfully updated.'}
      format.json { head :no_content }
    else
      format.html { render action: 'edit' }
      format.json { render json: @deals.errors, status: :unprocessable_entity }
    end
  end
end

Upvotes: 0

Related Questions