我一直在搜索数小时并逐一查看所有谷歌搜索结果...阅读RubyMoney,Money-Rails。我是rails的新手,我仍然无法理解如何为我的整个Ruby on Rails应用程序获取货币切换器。
在我的Gemfile中
gem 'money-rails'
gem 'json'
gem 'bigdecimal'
创建了config / initializers / money.rb
MoneyRails.configure do |config|
config.default_currency = :eur
end
<%= humanized_money_with_symbol (item.item_price) %>
将该数字格式化为视图中的货币。
如何通过欧盟银行或谷歌的自动费率更新获取Airbnb等货币选择器以更改网站的所有价格?我无法理解关于这个的RubyMoney文档...
答案 0 :(得分:0)
以下我将作为起点。
1)添加到 Gemfile :
gem 'google_currency'
2)添加到 config / initializers / money.rb :
MoneyRails.configure do |config|
config.default_currency = :eur
# set default bank to instance of GoogleCurrency
Money::Bank::GoogleCurrency.ttl_in_seconds = 86400
config.default_bank = Money::Bank::GoogleCurrency.new
end
3)在应用程序布局中的某处添加货币选择器,或者您认为应该使用您感兴趣的所有货币(:usd,:eur等)。使用此选择框中的on change
javascript 事件或按钮触发rails操作,将所选币种保存在会话变量上(让我们从现在开始调用会话[:货币] )并且还刷新当前页面(如果您在当前页面上显示某些价格 - 如果您只使用一个按钮,那么简单的redirect_to :back
会做否则,如果您的回复采用 js 格式,请使用window.location.reload();
)。行动看起来像这样:
def save_currency
session[:currency] = params[:currency]
respond_to do |format|
format.html { redirect_to :back }
end
end
在你的 routes.rb (替换控制器,无论你想要什么)这样的事情:
post '/controller/save_currency', to: 'controller#save_currency'
只有选择框和提交按钮丢失的表单 - 请按照您的意愿执行:)
4)添加帮助方法来渲染价格(假设您使用monetize
宝石将所有价格属性定义为money-rails
)。您要在网站上显示的所有价格都应使用此方法在视图上呈现。方法看起来像这样(你可以把它放在你的 application_helper.rb 上,如果你没有看到它更适合的其他地方):
def converted_price(price)
if session[:currency].present?
humanized_money_with_symbol(price.exchange_to(session[:currency]))
else
humanized_money_with_symbol(price)
end
end
这是一个简化版本,您还应该添加一些异常处理look at google_currency gem以获取更多相关文档。
5)在您要打印价格的所有视图中,使用与此类似的代码(我使用与您相同的示例):
<%= converted_price(item.item_price) %>
希望它有所帮助!