Ruby on Rails BigDecimal无法正确添加

时间:2015-01-16 19:22:06

标签: ruby-on-rails bigdecimal

我正在尝试制作一个表格,用户可以在其中输入一个号码(取款/存款),然后金额将显示在帖子中。但是,无论我怎么做,BigDecimals都不会加起来。

class MicropostsController < ApplicationController
  before_action :logged_in_user, only: [:create, :destroy]

  def create
    @micropost = current_user.microposts.build(micropost_params)
    if @micropost.save
      flash[:success] = "Micropost created!"
      current_user.update_attributes(deposit: deposits(@micropost.deposit), 
                                     withdraw: withdrawals(@micropost.withdraw),
                                     total: totals(@micropost.deposit, @micropost.withdraw)) 
      redirect_to root_url
    else
      @feed_items = []
      render 'static_pages/home'
    end
  end

  def deposits(money)
    return current_user.deposit + BigDecimal(money)
  end

  def withdrawals(money)
    return current_user.withdraw + BigDecimal(money)
  end

  def totals(dep, wit)
    return current_user.total + BigDecimal(dep) - BigDecimal(wit)
  end

  private

    def micropost_params
    params.require(:micropost).permit(:content, :deposit, :withdraw)
  end
end

那么当@ micropost.deposit = 2.3和@ micropost.withdraw = 2.4时,Ruby on Rails似乎将两者都舍入到最接近的整数,输出为4.0。

这也是我的表格

<%= form_for(@micropost) do |f| %>
  <%= render 'shared/error_messages', object: f.object %>
  <div class="field">
    <%= f.text_area :content, placeholder: "Compose new micropost..." %>
  </div>
  <div class="field">
    <%= f.text_field :deposit, placeholder: "Deposit. Input only positive numbers, e.g. 0.00" %>
  </div>
  <div class="field">
    <%= f.text_field :withdraw, placeholder: "Withdraw: Input only positive numbers, e.g. 0.00" %>
  </div>
  <%= f.submit "Post", class: "btn btn-primary" %>
<% end %>

1 个答案:

答案 0 :(得分:0)

我认为你有两个问题:

  1. BigDecimal - 如果您不希望它舍入为整数,则需要精度,因此BigDecimal(1.7,1)为2且BigDecimal(1.7,2)为1.7
  2. 撤销和存款字段中的数据类型可能是integer而不是decimal