首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Money-Rails Gem:模型中的Humanized_money

Money-Rails Gem:模型中的Humanized_money
EN

Stack Overflow用户
提问于 2015-08-19 04:30:28
回答 5查看 3K关注 0票数 5

在我的捐款模型中,我已经将amount_cents列货币化了

我需要人道版本的捐款金额(例如。643.50)在模型中,这样我就可以生成并发送一个PDF收据给捐献者。

我尝试过humanized_money(self.amount)和self.amount.humanized_money,但是得到了错误:

代码语言:javascript
复制
NoMethodError: undefined method `humanized_money' for #<Donation:0x007fa687ebb678>

我怎样才能在模型中得到这种人性化的形式?

代码语言:javascript
复制
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

以下是数据库模式:

代码语言:javascript
复制
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
EN

回答 5

Stack Overflow用户

回答已采纳

发布于 2018-03-14 18:57:34

不需要在模型中包括助手。

代码语言:javascript
复制
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)

github上的源代码

票数 1
EN

Stack Overflow用户

发布于 2016-01-08 20:01:03

在不加载ActionView::Base中的所有内容的情况下执行此操作。你可以直接做

代码语言:javascript
复制
return ActionController::Base.helpers.humanized_money sum
票数 5
EN

Stack Overflow用户

发布于 2017-09-16 00:40:44

包括ActionView::Base将为您的模型添加许多额外的内容,不要这样做。

取而代之的是这样做:

代码语言:javascript
复制
include MoneyRails::ActionViewExtension

这样,您就可以获得所有的money视图助手方法(在本文发布时为5)。

票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/32086603

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档