Reddirt
Reddirt

Reputation: 5953

How to pass a variable to render_to_string from a model?

I'm trying to pass a variable to render_to_string from a model.

This question is similar to How to pass variable to render_to_string?

I've read the answers in that question. I'm trying to use the locals. But, I still can't get it to work.

This is my model code:

pdf2 = CostprojectsController.new.render_to_string pdf: "Captital Projects.pdf", template: "costprojects/viewproject", encoding: "UTF-8", locals: {:@costproject => @costproject}

But, in the view costprojects/viewproject, @costproject is nil and costproject is nil

I've tried:

locals: {costproject: @costproject}
locals: {@costproject: @costproject}
locals: {:costproject => @costproject}

Thanks for the help!!

UPDATE1 (I appreciate the help)

I tried this (adding parens):

pdf2 = CostprojectsController.new.render_to_string(pdf: "Captital Projects.pdf", template: "costprojects/viewproject", encoding: "UTF-8", locals: {costproject: @costproject})

I added this line just before pdf2

raise @costproject.inspect

And I got:

#<Costproject id: 9, project_name: ...

In the view, should the passed var be @costproject

Upvotes: 0

Views: 2120

Answers (1)

patrickmcgraw
patrickmcgraw

Reputation: 2495

You could try something like:

controller = CostprojectsController.new
controller.instance_variable_set(:"@costproject", @costproject)  
pdf2 = controller.render_to_string(pdf: "Captital Projects.pdf", 
                                   template: "costprojects/viewproject", 
                                   encoding: "UTF-8")

The call to instance_variable_set should simulate setting @costproject in the body of a before_filter or controller action. This should make it available inside the call to render_to_string

Upvotes: 2

Related Questions