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!

Answers


@@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

Need Your Help

How can one click a button on different domain web page using Javascript or PHP

javascript php jquery

I have tried using iframes as shown below but it's not working.

Mountable engine routing error in Rails 4 after upgrade from Rails 3

ruby-on-rails ruby-on-rails-4 routing

I'm having some trouble with some mountable engines within our Rails 4.2.4 app. We recently (I know, it's sad how late we are to the game) upgrade from Rails 3.2.23. Our engine routes worked fine in