我通過簡單的計算器應用程序工作我的方式...困惑錢-Rails的寶石
試圖整合在它的錢,寶石,但是迷茫......
這是當前模式(如你可以看到,它沒有與_cents
結尾的列...和非常困惑是否需要_cents
部分...
當前架構
ActiveRecord::Schema.define(version: 20170301051956) do
# These are extensions that must be enabled in order to support this database
enable_extension "plpgsql"
create_table "tippies", force: :cascade do |t|
t.float "tip", null: false
t.decimal "cost", null: false
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
end
在模型中,我加入monetize :tip
& monetize: cost
...
我是否需要修改tip
和cost
列模式,即改造它是整數,並添加後_cents
一部分?
電流模型
class Tippy < ApplicationRecord
validates :tip, presence: true
validates :cost, presence: true
monetize :tip
monetize :cost
TIP_CHOICES = { "10%" => ".10", "20%" => ".20", "30%" => ".30", "40%" => ".40", "50%" => ".50",
"60%" => ".60", "70%" => ".70", "80%" => ".80", "90%" => ".90" }
def calculation_of_total_cost
cost + (tip * cost)
end
end
當我嘗試去到我的主頁(它設置到新頁面),我得到這個錯誤:
ArgumentError in TippiesController#new
Unable to infer the name of the monetizable attribute for 'tip'. Expected amount column postfix is '_cents'. Use :as option to explicitly specify the name or change the amount column postfix in the initializer.
它特指模型中的monetize :tip
...
Show.html.erb
<br/><br/>
<h1 class="text-center">Your Total Cost</h1>
<br/><br />
<table class="table table-striped">
<tr>
<td>
Cost of Your Meal:
</td>
<td>
<%= humanized_money_with_symbol @tippy.cost) %>
</td>
</tr>
<tr>
<td>
Tip You Picked:
</td>
<td>
<%= number_to_percentage(@tippy.tip * 100, format: "%n%", precision: 0) %>
</td>
</tr>
<tr>
<td>
The Total Cost:
</td>
<td>
<%= number_to_currency(@tippy.calculation_of_total_cost) %>
</td>
</tr>
</table>
new.html.erb
<br /><br />
<h1 class="text-center">Calculate Your Tip!</h1>
<%= render 'form', tippy: @tippy %>
_form.html.erb
<%= form_for(tippy, :html => {'class' => "form-horizontal"}) do |f| %>
<% if tippy.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(tippy.errors.count, "error") %> prohibited this tippy from being saved:</h2>
<ul>
<% tippy.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field form-group">
<%= f.label :cost_of_your_meal, class: "control-label" %>
<%= f.text_field :cost, class: "form-control" %>
</div>
<div class="field form-group">
<%= f.label :pick_your_tip, class: "control-label" %>
<%= f.select(:tip, Tippy::TIP_CHOICES, class: "form-control") %>
</div>
<div class="actions">
<%= f.submit class: "btn btn-primary btn-lg btn-block" %>
</div>
<% end %>
如何使這項工作?請讓我知道是否需要更多信息。謝謝
對所有**貨幣列使用小數類型(不是float)。 – max
@max,所以,重命名所有列以添加'_cents'並使其浮動? – user273072545345
money-rails有自己的遷移方法 - [閱讀文檔](https://github.com/RubyMoney/money-rails) – max