繁体   English   中英

Rails-编辑视图-无法保存到MySQL:使用number_to_currency帮助程序进行十进制

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

我有2个数据库列(使用mysql),一个为小数(10,2),另一个为字符串。

迁移看起来像。

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

在_form.html.erb部分中,我使用number_to_currency帮助器进行了以下操作。

<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>

首先,我在TOTALTAX字符串中有“ 3429.65”,在十进制中有“ 189900.00”。

当我在编辑视图中使用局部视图时。 一切都按照您的期望和我的数字呈现。 在他们的字段中,看起来很漂亮,这就是我想要的。 易于阅读。

但是,当我将表单提交给Edit(更新)时,我的字符串以“ $ 3,429.65”保存到数据库中,这是可以的,但是我的十进制保存为“ 0.00”。 我的数据怎么了?

其次,如果我返回并重新进入编辑视图,我的十进制(PRICE)显然显示为“ $ 0.00”,但是现在我的字符串(TOTALTAX)显示为“ $$ 3,429.65”。 每当我重新进入视图并更新时,它只会在前面加上$符号。

想法???

我尝试在模型中使用before_save钩子没有成功,代码看起来像。

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

我讨厌这样做,但它有效。 我仍然对其他解决方案持开放态度。

在控制器中,我劫持了参数,剥离了所有$和符号,然后将被入侵的参数哈希发送到.update方法。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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