I am trying to make a form, in which a user can input a number (withdraw/deposit) and then the amount will show in a post. But, whatever I tried, the BigDecimals do not add up.
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
So what happens is that when @micropost.deposit = 2.3 and @micropost.withdraw = 2.4, Ruby on Rails seems to round both to the nearest whole number, and the output is 4.0.
Here is also my form
<%= 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 %>
I think you have a 2 part problem:
BigDecimal(1.7,1)
is 2 and BigDecimal(1.7,2)
is 1.7integer
and not decimal