ruby-on-railsrails-activerecordmoney-rails

Money-Rails Gem: Humanized_money in Models


In my Donations Model, I have monetized the amount_cents column

I need the humanized version of the donation amount (Eg. 643.50) in the Model so I can generate and send a PDF receipt to the donor.

I've tried humanized_money(self.amount) and self.amount.humanized_money but get the error :

NoMethodError: undefined method `humanized_money' for #<Donation:0x007fa687ebb678>

How can I get this humanized form in the Models?

class Donation < ActiveRecord::Base
  belongs_to :donatable, polymorphic: true
  belongs_to :added_by_user, foreign_key: "added_by", class_name: "User"

  store_accessor :details, :method

  monetize :amount_cents

  def donations_this_week(branch_id)
    sum =  Donation.sum(:amount_cents).to_money
    return humanized_money(sum)
  end

  def receipt
    Receipts::Receipt.new(
        id: id,
        product: "GoRails",
        message: "This receipt is to acknowledge that we have received a donation with the below details from #{self.donatable.name}",
        company: {
            name: self.donatable.branch.organization.name,
            address: "#{self.donatable.branch.address_line_1}\n#{self.donatable.branch.address_line_2}\n#{self.donatable.branch.email}\n#{self.donatable.branch.legal_details}",
            email: self.donatable.branch.email,
            logo: self.donatable.branch.organization.logo.url(:medium),
        },
        line_items: [
            ["Date",           created_at.to_s],
            ["Donor Name", self.donatable.name],
            ["Amount",         humanized_money(self.amount)],
            ["Payment Method",     self.method],
        ]
    )
  end
end

Below is the database schema :

create_table "donations", force: :cascade do |t|
t.string   "donatable_type"
t.integer  "donatable_id"
t.integer  "amount_cents"
t.datetime "created_at",                  null: false
t.datetime "updated_at",                  null: false
t.datetime "date"
t.integer  "added_by"
t.jsonb    "details",        default: {}, null: false

Solution

  • Do NOT need to include the helper in your model.

    price_options = {
      :no_cents_if_whole => MoneyRails::Configuration.no_cents_if_whole.nil? ? true : MoneyRails::Configuration.no_cents_if_whole,
      :symbol => true
    }
    your_money_column.format(price_options)
    

    source code on github