我试图重现您的问题,但我只能重现弃用警告,您可以通过删除
define_method(:after_find) { }
声明。
我的代码:
class Testmodel < ActiveRecord::Base
def self.encode(*attr_names)
encoder = Encoder.new(attr_names)
before_save encoder
after_save encoder
after_find encoder
end
end
class Encoder
def initialize(attrs_to_manage) # We're passed a list of attributes that should be stored encoded in the database
@attrs_to_manage = attrs_to_manage
end
def before_save(model) # Before saving or updating, encode the attributes to their original encoding
@attrs_to_manage.each do |field|
model[field] = to_orig_encod(model[field])
end
end
def after_save(model) # After saving, encode them back to utf8
@attrs_to_manage.each do |field|
model[field] = to_utf8(model[field])
end
end
alias_method :after_find, :after_save # Do the same after finding an existing record
private
def to_orig_encod(var)
"foo"
end
def to_utf8(var)
"bar"
end
end
控制台测试:
ruby-1.9.2-p0 > Testmodel.create
=> #<Testmodel id: 3, name: nil, created_at: "2010-09-08 14:02:06", updated_at: "2010-09-08 14:02:06">
ruby-1.9.2-p0 > Testmodel.last
=> #<Testmodel id: 3, name: nil, created_at: "2010-09-08 14:02:06", updated_at: "2010-09-08 14:02:06">
ruby-1.9.2-p0 > Testmodel.encode('name')
=> [Testmodel(id: integer, name: string, created_at: datetime, updated_at: datetime)]
ruby-1.9.2-p0 > Testmodel.last
=> #<Testmodel id: 3, name: "bar", created_at: "2010-09-08 14:02:06", updated_at: "2010-09-08 14:02:06">
我一直在查阅
http://api.rubyonrails.org/classes/ActiveRecord/Callbacks.html
要理解你的问题:-)