我正在扩展并包括这些文件,但仍会收到:undefined method after_initialize for Play:Class
class Play
extend ActiveModel::Callbacks
extend ActiveModel::Naming
include ActiveModel::Validations
include ActiveModel::Validations::Callbacks
include ActiveModel::Conversion
after_initialize :process_data
#...
end
我正在使用Rails 4。
最佳答案
试用以下代码
class Play
extend ActiveModel::Naming
extend ActiveModel::Callbacks
define_model_callbacks :initialize, :only => :after
include ActiveModel::Validations
include ActiveModel::Validations::Callbacks
include ActiveModel::Conversion
attr_accessor :name
def initialize(attributes = {})
attributes.each do |name, value|
send("#{name}=", value)
end
run_callbacks :initialize do
puts 'initialize callback'
end
end
def attributes
return @attributes if @attributes
@attributes = {
'name' => name
}
end
end
#1.9.2-p290 :001 > Play.new(:name => 'The name')
#initialize callback
# => #<Play:0x00000006806050 @name="The name">
#1.9.2-p290 :002 >
这是资源Adding ActiveRecord-style callbacks to ActiveResource models
关于ruby-on-rails - Rails,将回调包含到无表模型中的正确方法是什么,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/17681789/