如何将变量从模型传递给 render_to_string?
Posted
技术标签:
【中文标题】如何将变量从模型传递给 render_to_string?【英文标题】:How to pass a variable to render_to_string from a model? 【发布时间】:2015-09-12 08:40:08 【问题描述】:我正在尝试将一个变量从模型传递给 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
为 nil,costproject
为 nil
我试过了:
locals: costproject: @costproject
locals: @costproject: @costproject
locals: :costproject => @costproject
感谢您的帮助!
UPDATE1(感谢您的帮助)
我试过这个(添加括号):
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
【问题讨论】:
尝试使用括号:CostprojectsController.new.render_to_string(pdf: "Captital Projects.pdf", template: "costprojects/viewproject", encoding: "UTF-8", locals: costproject: @costproject )
正确的调用应该是 pdf2 = CostprojectsController.new.render_to_string(template: "costprojects/viewproject", encoding: "UTF-8", locals: costproject: @costproject) - 是@调用render_to_string时正确设置了costproject var? - 你能用'layout: nil'选项试试这个电话吗?
【参考方案1】:
你可以试试这样的:
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
的调用应该模拟在before_filter
或控制器操作的主体中设置@costproject
。这应该可以在对render_to_string
的调用中使用它
【讨论】:
@Reddirt 如果您的意思是您有另一个名为@useremail
的变量,然后再次调用 instance_variable_set
但将 costproject
交换为 useremail
。以上是关于如何将变量从模型传递给 render_to_string?的主要内容,如果未能解决你的问题,请参考以下文章