Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
864 views
in Technique[技术] by (71.8m points)

ruby on rails - Deprecation warning for creating attribute 'currency'

I'm using Rails 3.2.3 with the money-rails gem and I've got a product model which has the following:

My model

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

My Test

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

Deprecation warning I'm getting.

% 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

How do I fix this deprecation warning?

Update

If I add 'currency' to the table it starts working. Should I have to do this though?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Apparently in Rails 3.2 and above arbitrary attributes (attributes not stored in the database) are no longer allowed. There doesn't seem to be a way around it.

Here is the commit for the deprecation message: https://github.com/rails/rails/commit/b2955edc and here is why: https://github.com/rails/rails/commit/50d395f96ea05da1e02459688e94bff5872c307b

In your case price_cents and currency still need to be stored in the database and then your composed class will take it from there.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...