Rails, which is the right way to include callbacks in a tableless model

I expand and include these files, but still get: 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 

I am using Rails 4.

+4
source share
2 answers

Try the following code

 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 > 

Here's a resource Adding ActiveRecord-style callbacks to ActiveResource models

+6
source

I don’t know if all ActiveModel overhead is needed, but you can do it with less code:

 class Play include ActiveModel::Model def initialize(attributes) super(attributes) after_initialize end private def after_initialize ... end end 
+4
source

Source: https://habr.com/ru/post/1491694/


All Articles