【问题标题】:Money-Rails Gem: How to make a select list for all currencies?Money-Rails Gem:如何为所有货币制作选择列表?
【发布时间】:2014-08-15 23:28:15
【问题描述】:

我正在使用money-rails gem 并想在我的视图中显示不同货币的列表,但我现在的代码不起作用。

我有我的Price 模型和字段in_centscurrency

create_table :prices do |t|
  t.integer :in_cents, default: 0, null: false
  t.string :currency, default: 'USD', null: false

现在,根据Money gem 和 Money-Rails 文档,我必须执行以下操作:

class Price < ActiveRecord::Base

  monetize :in_cents, as: "amount", with_model_currency: :in_cents_currency

  def all_currencies(hash)
    hash.keys
  end

比我对简单表单gem的看法:

= f.input :currency, collection: all_currencies(Money::Currency.table)
= f.input :amount, required: false

但这给了我错误:

undefined method `all_currencies' for #<#<Class:0xd154124>:0xd15bab4>

为什么?

附言

我想显示 ISO 代码和名称,如 United States Dollar (USD)

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-4 money-rails


    【解决方案1】:

    不确定这是最好的解决方案,但是我做了一个这样的助手:

      def currency_codes
        currencies = []
        Money::Currency.table.values.each do |currency|
          currencies = currencies + [[currency[:name] + ' (' + currency[:iso_code] + ')', currency[:iso_code]]]
        end
        currencies
      end
    

    【讨论】:

    • Money::Currency.table.values.map {} 怎么样
    【解决方案2】:

    最简单的解决方案:

    = f.select :currency, Money::Currency.table
    

    【讨论】:

      【解决方案3】:

      你的 all_currencies 方法是一个实例方法,你没有在实例上调用它。

      添加self.all_currencies,然后用Price.all_currencies调用它

      希望对你有帮助

      【讨论】:

      • 不知道为什么这会给我一个Wrong Number of Arguments 错误。
      • 啊,我明白了。不得不做Price.all_currencies(Money::Currency.table)。这确实具有所有 iso_codes 但不是我正在寻找的格式。像usd 这样的所有小写字母都没有货币名称。你知道我该怎么做United States Dollar (USD)吗?
      • 您将 Money::Currency.table 作为参数传递给 self.all_currencies 并调用返回小写货币缩写的键。我不知道 Money::Currency.table 中存储了哪些键/值,但尝试用 hash.values 替换 hash.keys,或者更好的是,检查散列并查看是否有其他键可以调用给你所需的输出。
      • Money::Currency.table.keys 比在模型上创建 all_currencies 方法更容易。
      猜你喜欢
      • 2015-07-20
      • 1970-01-01
      • 2015-08-15
      • 2016-12-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-22
      • 2016-08-23
      相关资源
      最近更新 更多