用于创建属性“货币”的弃用警告

时间:2012-05-15 07:27:39

标签: ruby-on-rails rspec currency

我正在使用Rails 3.2.3和money-rails gem,我有一个产品型号,其中包含以下内容:

我的模特

class Product < ActiveRecord::Base
  attr_accessible :name, :price

  composed_of :price,
  :class_name => "Money",
  :mapping => [%w(price_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") }


end

我的测试

require 'spec_helper'

describe Product do
  context "testing money gem" do
    it "creates product with price" do
      product = Product.create(:price => 200)
      product.price.should eq(200)
      product.price_cents.should eq(20000)
    end
  end
end

我得到的弃权警告。

% rspec spec/models/product_spec.rb

Product
  testing money gem
DEPRECATION WARNING: You're trying to create an attribute `currency'. Writing arbitrary attributes on a model is deprecated. Please just use `attr_writer` etc. (called from block (3 levels) in <top (required)> at /home/map7/project/spec/models/product_spec.rb:6)
    creates product with price

Finished in 0.06682 seconds
1 example, 0 failures

如何修复此弃用警告?

更新

如果我在表格中添加'currency',它就会开始工作。我应该这样做吗?

2 个答案:

答案 0 :(得分:14)

显然,在Rails 3.2及更高版本中,不再允许任意属性(未存储在数据库中的属性)。似乎没有办法绕过它。

以下是弃用邮件的提交:https://github.com/rails/rails/commit/b2955edc 这就是原因:https://github.com/rails/rails/commit/50d395f96ea05da1e02459688e94bff5872c307b

在您的情况下,price_cents和货币仍然需要存储在数据库中,然后您的组合类将从那里获取它。

答案 1 :(得分:1)

在我的模型中添加'currency:string'