2013-07-16 52 views
4

我伸出並且包括那些文件,但仍然無表模型以適當的方式獲得:undefined method after_initialize for Play:ClassRails的,什麼是包括的回調

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

+0

似乎你想要的類是ActiveRecord的一部分,而不是ActiveModel? http://api.rubyonrails.org/classes/ActiveRecord/Callbacks.html – Zabba

回答

6

試試以下代碼

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

+1

Yeap,謝謝,那就是我一直在尋找的東西。 – nateless

4

I D不知道你是否需要所有的ActiveModel開銷,但你可以使用較少的代碼:

class Play 
    include ActiveModel::Model 

    def initialize(attributes) 
    super(attributes) 
    after_initialize 
    end 

    private 

    def after_initialize 
    ... 
    end 
end 
+0

在這種情況下'default_player_options'會是什麼?具有默認屬性的散列? – Daniel

+0

@丹尼爾對不起,那不應該在那裏。如果你想在類方法中使用默認選項,那就是了。 –

+0

這是否完全取代'initialize'方法?不確定。 – hlcs