2015-06-02 94 views
4

我試圖在我的Rails 4應用程序中使用貨幣(與金錢軌道寶石)。金錢導軌寶石與軌道4 - 實例貨幣

你如何讓用戶只提交一個數字美元?當我輸入100時,我得到1美元而不是100美元。

在我的模型,我有:

monetize :participation_cost_pennies, with_model_currency: :participation_cost_currency 

我使用的情況下的貨幣,所以用戶在選擇相關貨幣。我的表格有參與成本,參與成本便士和參與成本貨幣的列。

在我的形式,我有:

<%= par.select :participation_cost_currency, 
          options_for_select(major_currencies(Money::Currency.table)), 
          label: false, 
          prompt: "Select your costs currency" %> 

      <%= par.input :participation_cost, label: false, placeholder: 'Whole numbers only', :input_html => {:style => 'width: 250px; margin-top: 20px', class: 'response-project'} %> 

在我看來,我有:

<%= money_without_cents_and_with_symbol @project.scope.participant.participation_cost %> 

通過在形式與參與成本替代的參與成本便士',我得到的數顯示爲一個整數沒有美分我現在得到10,000美元,當我輸入100(所以相反的問題,因爲它是加入002到我的輸入結束

+0

這聽起來像一個強烈的參數問題。你有沒有在控制器中正確列出你的參數? – rkamun1

+0

嗨,伯特利爵士,我已經白色列出了每個參與者和項目控制員參與者模型的參數。我沒有將它們添加到我的示波器控制器。我不認爲我需要他們,因爲範圍嵌套在項目中。問題用白名單params更新。 – Mel

回答

2

看來,您使用price列的數據庫內,並要求用戶輸入完全相同的輸入。這兩個不同的setter/getters。請嘗試以下操作:

# add migration 
rename_column :products, :price, :price_cents 


# set monetize for this field inside the model 
class Product 
    monetize :price_cents 
end 

# inside form use .price instead of .price_cents method 
f.text_field :price 

在美元這種情況下,用戶設定的價格,它會自動轉換爲美分,至其店內price_cents場。

+0

謝謝 - 已經工作了 – Mel

1

money-rails寶石p價格保存爲in cents,所以100的產出爲1美元是正常的,因爲它確實是100美分。 100美元將是10000.這是有意的,到avoid floating point rounding errors

如果您想在應用程序中處理美元,您可以編寫一個幫助函數將輸入轉換爲分。

+0

如何編寫助手功能? – Mel

+0

將輸入乘以10. – p4sh4

1

假設您的表格中有price_cents列。 你可以試試這個代碼monitize之前,美元金額轉換爲仙:

monetize :price_cents 
before_save :dollars_to_cents 

def dollars_to_cents 
    #convert dollar to cents 
    self.price_cents = self.price_cents * 100 
end