Rails: money gem converts all amounts to zero

后端 未结 2 1753
醉梦人生
醉梦人生 2020-12-24 09:30

I\'m trying to use the money gem to handle currency in my app but I\'m running into a strange error. This is what I have in my \"record\" model:

composed_of          


        
2条回答
  •  天命终不由人
    2020-12-24 10:23

    tl;dr: change :amount to :price or :anything_else.

    I've concluded that :amount is a keyword used somewhere in the money gem, so using it in your application causes problems.

    It's a stretch, but the author uses the word amount in the first line of the documentation to describe what it does.

    "Provides a Money class which encapsulates all information about an certain amount of money, such as its value and its currency." http://money.rubyforge.org/

    In my Rails 3.0 project I've got 3 very similar models that extend the money class: Labor, Part, and Payment.

    Labor and Part work fine using the attribute :price, but I wanted to use :amount in my Payment model, because it sounded better when reading aloud or in my head.

    The problem I experienced is that Payment would take valid form input, toss out the :amount, save 0 in the database, and throw an undefined method `round' for nil:NilClass error, upon viewing the record:

    I'm pretty sure that 0 is a symptom of nil getting converted by my migration options (:null => false, default => 0). I ruled out the View by debugging with safari web inspector, and then the Controller by raising and inspecting each variable. This sort of problem in the Model doesn't make a lot of sense, so I figured it had to be money. Then, I found this thread, and put it all together.

    After rolling back the migration, and changing all :amount references to :price, it works perfectly.

    I know this thread is a few months old, but hopefully this will help someone else avoid this pitfall in the future.

    In the meantime, I'll be sticking to :price.

提交回复
热议问题