我试图从模型中将变量传递给render_to_string。
此问题与How to pass variable to render_to_string?
类似我已经阅读了那个问题的答案。我试图使用locals
。但是,我仍然无法让它发挥作用。
这是我的型号代码:
pdf2 = CostprojectsController.new.render_to_string pdf: "Captital Projects.pdf", template: "costprojects/viewproject", encoding: "UTF-8", locals: {:@costproject => @costproject}
但是,在视图costprojects/viewproject
中,@costproject
为零,costproject
为零
我试过了:
locals: {costproject: @costproject}
locals: {@costproject: @costproject}
locals: {:costproject => @costproject}
感谢您的帮助!!
UPDATE1(我很感谢帮助)
我试过这个(添加parens):
pdf2 = CostprojectsController.new.render_to_string(pdf: "Captital Projects.pdf", template: "costprojects/viewproject", encoding: "UTF-8", locals: {costproject: @costproject})
我在pdf2
raise @costproject.inspect
我得到了:
#<Costproject id: 9, project_name: ...
在视图中,传递的var应该是@costproject
答案 0 :(得分:2)
您可以尝试以下方式:
controller = CostprojectsController.new
controller.instance_variable_set(:"@costproject", @costproject)
pdf2 = controller.render_to_string(pdf: "Captital Projects.pdf",
template: "costprojects/viewproject",
encoding: "UTF-8")
对instance_variable_set
的调用应模拟@costproject
或控制器操作正文中的before_filter
设置。这应该可以在render_to_string