5

I'm using the money-rails gem and want to show in my view a list of different currencies but the code I have now isn't working.

I have my Price model and the fields in_cents and currency:

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

Now according to the Money gem and Money-Rails docs I had to do something like:

class Price < ActiveRecord::Base

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

  def all_currencies(hash)
    hash.keys
  end

Than my view with simple form gem:

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

But this gives me the error:

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

Why?

P.S.

I want to show the ISO Code and the name like United States Dollar (USD).

Community
  • 1
  • 1
user2784630
  • 796
  • 1
  • 8
  • 19

3 Answers3

15

Not sure this is the best solution however I made a helper as such:

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

Most simple solution:

= f.select :currency, Money::Currency.table
Yshmarov
  • 3,450
  • 1
  • 22
  • 41
2

Your all_currencies method is an instance method, and you're not calling it on an instance.

Add self.all_currencies, and then call it with Price.all_currencies

Hope this helps

JamesDullaghan
  • 1,230
  • 11
  • 12
  • Not sure why this throws me a `Wrong Number of Arguments` error. – user2784630 Aug 16 '14 at 01:30
  • 1
    Ah, I see now. Had to do `Price.all_currencies(Money::Currency.table)`. This does have all the iso_codes but not in the format that I'm looking for. There all lowercase like `usd` and without the name of the currency. You know how I could do `United States Dollar (USD)`? – user2784630 Aug 16 '14 at 01:33
  • 1
    You are passing in Money::Currency.table as the argument to self.all_currencies and calling keys which is returning lowercase currency abbreviations. I don't know what keys/values are stored in Money::Currency.table, but try replacing hash.keys with hash.values, or better yet, inspect the hash and see if there are other keys you can call to give you the desired output. – JamesDullaghan Aug 17 '14 at 19:05
  • Easier to just do Money::Currency.table.keys instead of creating an all_currencies method on the model. – Andrew Feb 24 '17 at 19:05