money-rails
money-rails copied to clipboard
Rails 8: Cannot change default currency
In the latest rails 8.0, I could not seem to change the default currency from usd to gbp.
Things I've tried:
# initializers/money.rb
MoneyRails.configure do |config|
config.default_currency = :gbp
# config.default_currency = -> { :gbp }
end
Have also tried, in model:
# Meal.rb
register_currency :gbp # does nothing
# with_currency does nothing
monetize :price_cents, with_currency: :gbp
In rails console
Meal.last.price.currency.name #= "United States Dollar"
A workaround was to use a callback in the model:
[...]
after_initialize do |meal|
self.price_currency = Money::Currency.new(:gbp)
# If we kept register_currency :gbp, we could do:
# self.price_currency = Meal.currency
end
Nothing actually works as per documentation. Has this issue been addressed, but not reflect on the documentation?
Thanks
I suspect the migration that adds your Meal record to the database schema is using "USD". This can happen if you set the default currency after creating and running the migration.
Running bin/rails console with your initializer/money.rb on Rails 8.0.2 (Ruby 3.4.4), I get
test(dev)> Money.default_currency.id
=> :gbp
meal = Meal.new(price: 5)
=>
#<Meal:0x00007f8fbf400780
...
test(dev)> meal.price.currency.name
=> "British Pound"
For completeness' sake, app/model/meal.rb has
class Meal < ApplicationRecord
monetize :price_cents
end
and the migration looks like
class CreateMeals < ActiveRecord::Migration[8.0]
def change
create_table :meals do |t|
t.monetize :price
t.timestamps
end
end
end
which yields the following in db/schema.rb after bin/rails db:migrate
ActiveRecord::Schema[8.0].define(version: 2025_05_25_122540) do
create_table "meals", force: :cascade do |t|
t.integer "price_cents", default: 0, null: false
t.string "price_currency", default: "GBP", null: false
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
end