Prevent caching on exception in Ruby on Rails

Go To StackoverFlow.com

0

How can I prevent caching on exception? I have this action:

caches_page :index
...
def index
  if params[:city]
    city = City.find(params[:city])
    @shows = city.shows
  else
    @shows = Show.all
  end
...

If find crashed with ActionRecord::RecordNotFound nothing cached - it's ok. But I don't want this exception in my log file too. But if I:

  begin
    city = City.find(params[:city])
  rescue ActiveRecord::RecordNotFound
    render :nothing => true
    return
  end

Empty page cached!

What I suppose to do in this situation?

2012-04-04 06:18
by Donotello


0

Try :

caches_page :index, :if => :city_exists?

private

def city_exists
  city = City.find(params[:city])
  !city.nil? ? true : false
end

And I think you can use action caching or fragment caching .

Take a look into details for Extending Caching.

2012-04-04 06:34
by Vik
I cache json page with shows for city and I think page caching is the best choice (maybe not - I just started learning rails). But your solution requires one additional database request for city (I need it in my controller) - my be there is other options.. - Donotello 2012-04-04 06:54
hope so. Suggest to use fragment caching. Take a look on http://broadcastingadam.com/2011/05/advancedcachingin_rail - Vik 2012-04-04 07:06
Ads