Skip to content

Document that order of attributes matters when expect_whole_subunits is enabled #708

Open
@tagliala

Description

@tagliala

Hello,

we are in a situation where we want to take advantage of Monetize parser to deal with . and , (ref: #701)

It is worth to report that the order of fields matters because how the parser works

The parser expects that the currency is being already set when parse the amount, and this makes the order of assignment important, creating issues with currencies with a number of decimal points different from 2

Example:

# initializer
Monetize.expect_whole_subunits = true

MoneyRails.configure do |config|
  # Should not matter, added just to remove the deprecations
  config.rounding_mode = BigDecimal::ROUND_HALF_DOWN 
  config.locale_backend = :i18n
end

# Model
class Product < ApplicationRecord
  monetize :price_cents
end

Result

> Product.new(price_currency: 'JOD', price: '1.000').price
=> #<Money fractional:1000 currency:JOD>

Product.new(price: '1.000', price_currency: 'JOD').price
=> #<Money fractional:1000000 currency:JOD>

Solution

In rails, the order of permitted_params will matter, so you want to have something like this:

params.require(:product).permit(:price_currency, :price)
> params.require(:product).permit(:price, :price_currency)
#<ActionController::Parameters {"price"=>"123", "price_currency"=>"USD"} permitted: true>

> params.require(:product).permit(:price_currency, :price)
#<ActionController::Parameters {"price_currency"=>"USD", "price"=>"123"} permitted: true>

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions