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

ruby-on-rails – Rails:money gem将所有数量转换为零

发布时间:2020-12-16 22:01:21 所属栏目:百科 来源:网络整理
导读:我试图使用 money gem来处理我的应用程序中的货币,但我遇到了一个奇怪的错误.这是我在“记录”模式中所拥有的: composed_of :amount,:class_name = "Money",:mapping = [%w(cents cents),%w(currency currency_as_string)],:constructor = Proc.new { |cent
我试图使用 money gem来处理我的应用程序中的货币,但我遇到了一个奇怪的错误.这是我在“记录”模式中所拥有的:
composed_of :amount,:class_name => "Money",:mapping => [%w(cents cents),%w(currency currency_as_string)],:constructor => Proc.new { |cents,currency| Money.new(cents || 0,currency || Money.default_currency) },:converter => Proc.new { |value| value.respond_to?(:to_money) ? value.to_money : raise(ArgumentError,"Can't convert #{value.class} to Money") }

amount是一个整数.

当我创建一个新的记录时,它将忽略我放在金额字段中的任何值,并将其默认为0.有没有什么我需要添加到表单?

我使用的是rails 3.0.3,而gem gem版本是3.5.5

解决方法

编辑:在答案结束时增加了奖金

那么你的问题对我很有兴趣,所以我决定尝试一下自己.

这样做正常:

1)产品迁移:

create_table :products do |t|
  t.string :name
  t.integer :cents,:default => 0
  t.string :currency
  t.timestamps
end

2)产品型号

class Product < ActiveRecord::Base

   attr_accessible :name,:cents,:currency

  composed_of :price,"Can't convert #{value.class} to Money") }
end

3)表格:

<%= form_for(@product) do |f| %>
  <div class="field">
    <%= f.label :name %><br />
    <%= f.text_field :name %> 
  </div>
  <div class="field">
    <%= f.label :cents %><br />
    <%= f.text_field :cents %>
  </div>
  <div class="field">
    <%= f.label :currency %><br />      
   <%= f.select(:currency,all_currencies(Money::Currency::TABLE),{:include_blank => 'Select a Currency'}) %>
  </div>
  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>

4)产品助手(手工制作):

module ProductsHelper
  def major_currencies(hash)
    hash.inject([]) do |array,(id,attributes)|
      priority = attributes[:priority]
      if priority && priority < 10
        array ||= []
        array << [attributes[:name],attributes[:iso_code]]
      end
      array
    end
  end

  def all_currencies(hash)
    hash.inject([]) do |array,attributes)|
      array ||= []
      array << [attributes[:name],attributes[:iso_code]]
      array
    end
  end
end

奖金:

如果你想添加货币汇率:

1)你的宝石文件

gem 'json' #important,was not set as a dependency,so I add it manually
gem 'google_currency'

2)初始化器

在你的initializer文件夹中创建money.rb并将其放在里面:

require 'money'
require 'money/bank/google_currency'
Money.default_bank = Money::Bank::GoogleCurrency.new

重新启动服务器

3)玩!

无论你身在何处,都可以交换钱.

Product.first.price.exchange_to('USD')

显示与漂亮的渲染:

Product.first.price.format(:symbol => true)

(编辑:李大同)

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

    推荐文章
      热点阅读