开发者

Disabling model's after_find only when called from certain controllers

开发者 https://www.devze.com 2022-12-24 22:40 出处:网络
I have an after_find callback in a model, but I need to disable it 开发者_运维问答in a particular controller action e.g.

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

精彩评论

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

关注公众号