开发者

Rails callback for the equivalent of "after_new"

Right now I cant find a way to generate a callback between lines 1 a开发者_如何学Pythonnd 2 here:

f = Foo.new
f.some_call
f.save!

Is there any way to simulate what would be effectively an after_new callback? Right now I'm using after_initialize but there are potential performance problems with using that since it fires for a lot of different events.


You can use the after_initialize callback

# app/models/foo.rb
class Foo < ActiveRecord::Base
  after_initialize :some_call

  def some_call
    puts "Who you gonna call?"
  end
end

# rails console
> foo = Foo.new # => "Who you gonna call?"
> foo = Foo.first # => "Who you gonna call?"

Beware after_initialize is triggered every time ActiveRecord do a Foo.new (calls like new, find, first and so on) see the Rails Guide

So you probably want something like this after_initialize :some_call, :if => :new_record?

# app/models/foo.rb
class Foo < ActiveRecord::Base
  after_initialize :some_call, :if => :new_record?

  def some_call
    puts "Who you gonna call?"
  end
end

# rails console
> foo = Foo.new # => "Who you gonna call?"
> foo = Foo.first


Define a constructor for Foo and do what you need to do there.

An alternate solution would be to look into using after_initialize but that may not do quite what you expect.


If this is a Active Record model, then after_initialize is the correct way to handle callbacks after object creation. The framework itself makes certain assumptions about the way objects will be created from the database. Performance should not be a concern unless you have some long-running task being triggered in the callback, in which case you probably need to rethink the strategy.

If not an AR model, you can create an initialize method in your object and place the code there.

There are a number of other callbacks available depending on want you want to do, including after_create (called when a new record is created).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜