开发者

Disabling model's after_find only when called from certain controllers

I have an after_find callback in a model, but I need to disable it 开发者_运维问答in a particular controller action e.g.

def index
  @people = People.find(:all) # do something here to disable after_find()?
end

def show
  @people = People.find(:all) # after_find() should still be called here!
end

What is the best way to do it?

  1. Can I pass something in to .find to disable all/particular callbacks?
  2. Can I somehow get the controller name in the model and not execute the callback based on the controller name (I don't like this)..?

Help!


@@callback_after_find

don't forget restore it. maybe its more better.

class People
  def self.skip_after_find
    @@callback_after_find = false
    yield
  ensure
    @@callback_after_find = true
  end 
  def after_find
    return unless @@callback_after_find
    ...
  end
  private
  @@callback_after_find = true
end

People.skip_after_find do
  @people = People.find(:all) # do something here to disable after_find()?
end


You can add a flag on your model to define if you want execute or not after_find.

class People
  @@callback_after_find = true
  def after_find
    return unless @@callback_after_find
    ...
  end
end

In your controller you can now activate or not this callback

def index
  People.callback_after_find = false
  @people = People.find(:all) # do something here to disable after_find()?
end

def show
  @people = People.find(:all) # after_find() should still be called here!
end
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜