0

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

Community
  • 1
  • 1
Reddirt
  • 5,913
  • 9
  • 48
  • 126
  • Try using parenthesis: `CostprojectsController.new.render_to_string(pdf: "Captital Projects.pdf", template: "costprojects/viewproject", encoding: "UTF-8", locals: { costproject: @costproject })` – MrYoshiji Jun 25 '15 at 16:20
  • the correct call would be pdf2 = CostprojectsController.new.render_to_string(template: "costprojects/viewproject", encoding: "UTF-8", locals: {costproject: @costproject}) - is the @costproject var setted correctly when calling render_to_string? - could you try the call with 'layout: nil' option? – Florian Eck Jun 25 '15 at 16:42

1 Answers1

2

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

patrickmcgraw
  • 2,465
  • 14
  • 8
  • @Reddirt if you mean you have another variable called `@useremail` then make another call to `instance_variable_set` but swap `costproject` for `useremail`. – patrickmcgraw Jun 25 '15 at 20:15