2015-01-16 4 views
0

Я пытаюсь создать форму, в которой пользователь может ввести номер (снять/внести), а затем сумма будет отображаться в сообщении. Но, что бы я ни пытался, BigDecimals не складываются.Ruby on Rails BigDecimal не правильно добавляется

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

Что такое 'тип поля'' deposit' и 'exit' в schema.rb? –

+0

у вас это попробовали. 'BigDecimal.new (деньги)' Я думаю, что это сработает –

+0

Спасибо @ShamsulHaque! – Steve

ответ

0

Я думаю, что у вас есть проблема с 2 часть:

  1. BigDecimal - требует точности, если вы не хотите, чтобы округлить до целого, так BigDecimal(1.7,1) 2 и BigDecimal(1.7,2) 1,7
  2. Типы данных на отзывать и депозитные поля могут быть integer и не decimal
+0

Большое спасибо @eabraham! Это были мои ошибки – Steve