Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Money-Rails Gem: How to make a select list for all currencies?

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).

like image 529
user2784630 Avatar asked Aug 15 '14 23:08

user2784630


2 Answers

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
like image 75
SimonKiteley Avatar answered Oct 05 '22 12:10

SimonKiteley


Most simple solution:

= f.select :currency, Money::Currency.table
like image 42
Yshmarov Avatar answered Oct 05 '22 13:10

Yshmarov