Rails,将回调包含在无表格模型中的正确方法是什么

时间:2013-07-16 16:15:22

标签: ruby-on-rails

我正在扩展并包含这些文件,但仍会收到: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。

2 个答案:

答案 0 :(得分:9)

尝试以下代码

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 :(得分:6)

我不知道您是否需要所有ActiveModel开销,但您可以用更少的代码来完成:

class Play
  include ActiveModel::Model

  def initialize(attributes)
    super(attributes)
    after_initialize
  end

  private

  def after_initialize
    ...
  end
end