不能访问的ActiveRecord增变器中的块 [英] can't access ActiveRecord mutators in a block
问题描述
我是个Rails的控制器中,我试图访问我的实例变量在一个块: 这给出了一个错误,说没有办法字段1的无:
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
难道这有什么做的ActiveRecord的块访问或实例变量?
Could this have something to do with ActiveRecord accessors or instance variables in a block?
推荐答案
这是怎么回事,因为内部的块code在对虾:: Document对象的上下文中执行。让我们去这里面code:
That's happening because code inside block is executed in context of Prawn::Document object. Let's go inside this code:
module Prawn
class Document
def self.generate(filename,options={},&block)
pdf = new(options,&block)
pdf.render_file(filename)
end
def initialize(options={},&block)
if block
block.arity < 1 ? instance_eval(&block) : block[self]
end
end
end
end
正如你所看到的,块
与执行文件
对象自
。它试图找到@model为自实例变量
,不能做到这一点,并返回零
。如果使用本地变量模式
,你得到倒闭的帮助和code正常工作
As you can see, block
is executed with Document
object as self
. It try to find @model as instance variable of self
, can't do this and return nil
. If you use local variable model
, you get help of closures and your code is working properly
这篇关于不能访问的ActiveRecord增变器中的块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!