1

I have this piece of code in a partial on some code for rails 2.3.14:

<% cache "some_partial_#{some_id}" do %>
....
<% end %>

Works fine when rendering it in a view but I get:

undefined method `fragment_for' for nil:NilClass

when I try to do this in a model:

 ActionView::Base.new("app/views").render(:partial => "home/temp"}

I can see the issue occuring in actionpack-2.3.14/lib/action_view/helpers/cache_helper.rb:35

 def cache(name = {}, options = nil, &block)
    @controller.fragment_for(output_buffer, name, options, &block)
 end

I'm not sure what exactly it expects to find in @controller.

Razvan
  • 43
  • 5

2 Answers2

0

In short: don't render partials from models - they should contain only business-logic. Error occurs since cache invokes controller object which you don't have initialized since you are bypassing view rendering logic here.

UPDATE:

The only way i see it is to get controller instance and pass it as param. How to get controller instance inside model is up to you. I think this question could be helpful Try

ActionView::Base.new("app/views", {}, @your_controller_instance).render(:partial => "home/temp")
Community
  • 1
  • 1
Vadym Chumel
  • 1,766
  • 13
  • 20
  • While I do agree that it's incredibly bad practice to render from models, it's one of those situations where I don't really have a choice since a lot of this big app relies on that function working like that. I tried overriding def cache ... and placing a controller ||= ApplicationController but as expected ApplicationController doesn't really define fragment_for anywhere, so I guess it's waiting for something else in that @controller, just not sure what. – Razvan Oct 02 '12 at 07:44
0

You may be able to add:

include ActionController::Caching

to your class.

BananaNeil
  • 10,322
  • 7
  • 46
  • 66