我正在尝试制作一个表格,用户可以在其中输入一个号码(取款/存款),然后金额将显示在帖子中。但是,无论我怎么做,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 %>
答案 0 :(得分:0)
我认为你有两个问题:
BigDecimal(1.7,1)
为2且BigDecimal(1.7,2)
为1.7 integer
而不是decimal