问题
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.
回答1:
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")
回答2:
You may be able to add:
include ActionController::Caching
to your class.
来源:https://stackoverflow.com/questions/12685782/undefined-method-fragment-for-for-nilnilclass-on-render-partial-with-cache