I am inside a Rails controller and I am trying to access my instance variable in a block: This gives an error saying that "no method field1 for Nil":
Prawn::Document.generate("hello.pdf") do
@model.field1
end
However, if I do this, then it works:
my_model = @model
Prawn::Document.generate("hello.pdf") do
my_model.field1
end
Could this have something to do with ActiveRecord accessors or instance variables in a block?
That's happening because code inside block is executed in context of Prawn::Document object. Let's go inside this code:
As you can see,
block
is executed withDocument
object asself
. It try to find @model as instance variable ofself
, can't do this and returnnil
. If you use local variablemodel
, you get help of closures and your code is working properly