我一直在使用我们的rails 2.3应用程序中的一个控制器,并且我遇到了使用helper_method中指定的实例变量的问题。最初,情况是这样的:
home_controller.rb:
class HomeController < ActionController::Base
def index
end
def popular
@popular_questions = PopularQuestion.paginate :page => params[:page],
<some complex query>
end
end
home_helper.rb:
module HomeHelper
def render_popular_questions
@popular_questions = PopularQuestion.paginate :page => 1,
<some complex query>
render :partial => 'popular'
end
end
home/index.html.haml
-cached do
.popular=render_popular_questions
home/popular.html.haml
=render :partial => 'popular'
home/_popular.html.haml
-if @popular_questions.length > 0
<show stuff>
点击/或/热门显示了相应的热门问题框。
现在,由于查询非常复制,并且由于paginate默认使用正确的页面,因此我将其重构为:
home_controller.rb:
class HomeController < ActionController::Base
helper_method :get_popular_questions
def index
end
def popular
get_popular_questions
end
private
def get_popular_questions
@popular_questions = PopularQuestion.paginate :page => params[:page],
<some complex query>
end
end
home_helper.rb:
module HomeHelper
def render_popular_questions
get_popular_questions
render :partial => 'popular'
end
end
现在当我去/时,我得到了
You have a nil object when you didn't expect it!
You might have expected an instance of Array.
The error occurred while evaluating nil.length
在home / _popular.html.haml
的第1行中被提升模板似乎无法访问从帮助程序内调用的helper_methods中设置的变量。我在某个地方犯了错误吗?如果没有,我如何使用助手的helper_method中指定的实例变量?
答案 0 :(得分:1)
将它们作为参数和局部变量传递:
home_controller.rb:
class HomeController < ActionController::Base
helper_method :get_popular_questions
def index
end
def popular
@popular_questions = get_popular_questions
end
private
def get_popular_questions
# remember that the final statement of a method is also the return-value
PopularQuestion.paginate :page => params[:page],
<some complex query>
end
end
home_helper.rb:
module HomeHelper
def render_popular_questions
questions = get_popular_questions
render :partial => 'popular', :locals => {:questions => questions}
end
end
现在在你的部分,使用“问题”而不是“@popular_questions” 只需确保“热门”的主模板也需要填充此局部变量。