I currently have the money gem installed via money-rails
and it's working great. I have a monetized object called :default_price
and :default_price_cents
and am using a :currency
column to define the currencies. I also have a :default_packs
column which is a user defined integer that's monetized, and a Pack model which stores a new entry every day with a :date
column and a :amount
column.
Here's my user.rb
has_many :packs
register_currency :usd
monetize :default_price_cents, with_model_currency: :currency
monetize :default_price, with_model_currency: :currency
monetize :daily_saving_potential, with_model_currency: :currency
monetize :total_saving_potential, with_model_currency: :currency
monetize :total_money_spent, with_model_currency: :currency
monetize :total_savings, with_model_currency: :currency
def daily_saving_potential
return default_price * default_packs
end
def total_saving_potential
days = self.packs.count
return days * daily_saving_potential
end
def total_money_spent
amount = self.packs.map(&:amount).sum
return amount
end
def total_savings
return total_saving_potential - total_money_spent
end
The Problem
total_money_spent
sums all the entries of the :amount field from my Pack model. The problem arises that when total_savings
is called upon in my view, I get an error saying Unknown Method "exchange_to" for 0:fixnum
.
The interesting thing is that if I use :default_price_cents
instead of :default_price
in daily_saving_potential
, then I don't get the error, but my custom defined fields in the model display the default currency instead of the currency defined by the user, whereas the default_price
field displays the right currency defined by the user. Perhaps the issue has to do with the fact that I'm multiplying money objects with a non-money object from my Pack model? Regardless, the issue arises when I subtract the total_money_spent
from total_saving_potential
Let me know if you need more information, and all help is greatly appreciated!
I haven't worked with this gem, but it doesn't look like you've followed the read-me for the money-rails gem
https://github.com/RubyMoney/money-rails
Assuming you have a field in the model :default_price_cents
you can do...
monetize :default_price_cents, with_model_currency: :currency
... and this will automatically give you a monetzed field called ':default_price`. You don't need to define it and you don't need to "monetize" it, it's already a money attribute.
Similarly, you should be creating methods called daily_saving_potential_cents
and total_saving_potential_cents
and total_money_spent_cents
etc etc etc. You will automatically have a method daily_saving_potential
, and total_saving_potential
and so on.
In your method calculations use the raw (.._cents) attributes.