加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – Money-Rails Gem:模型中的Humanized_money

发布时间:2020-12-17 03:24:41 所属栏目:百科 来源:网络整理
导读:在我的捐赠模型中,我已将amount_cents列货币化 我需要模型中捐赠金额的人性化版本(例如643.50),这样我就可以生成并向捐赠者发送PDF收据. 我尝试过humanized_money(self.amount)和self.amount.humanized_money,但是得到了错误: NoMethodError: undefined met
在我的捐赠模型中,我已将amount_cents列货币化

我需要模型中捐赠金额的人性化版本(例如643.50),这样我就可以生成并向捐赠者发送PDF收据.

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

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

如何在模型中获得这种人性化的形式?

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

以下是数据库架构:

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

解决方法

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

从错误消息中可以看出,您正在为Donation对象调用humanized_money帮助器方法,而不是Money对象.这就是它失败的原因.

如果您已经正确地将amount_cents列货币化,那么自动地,您的金额列将是Money类型,即Money对象,您可以将其作为参数传递给humanized_money帮助方法,如下所示:

humanized_money amount

我会说,检查您的金额类型,并确保它是一个Money对象,如果您正确地通过捐赠模型的amount_cents列货币化它应该是.这就是为什么它不适用于这种情况.

更新

看起来humanized_money是在money-rails gem的action_view_extension中定义的,并且预计仅在视图中工作.不在模特中.

这个问题的一个可能的解决方案是在模型中包含ActionView::Base模块,这将使humanized_money方法在模型中可用.然后你可以在你的模型中调用humanized_money,如:

include ActionView::Base
 humanized_money(sum)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读