加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – ruby?? instance_variable_get返回nil

发布时间:2020-12-17 02:27:36 所属栏目:百科 来源:网络整理
导读:我对instance_variable_get方法有一个问题,因为它总是使用我的一个对象实例返回nil对象. 这是我的代码: logger.info "ASDF: " + @d_tree.inspectlogger.info "ASDF: " + @d_tree.instance_variable_get(:@content); 输出是: ASDF: #DTree id: 11,parent_id
我对instance_variable_get方法有一个问题,因为它总是使用我的一个对象实例返回nil对象.
这是我的代码:

logger.info "ASDF: " + @d_tree.inspect
logger.info "ASDF: " + @d_tree.instance_variable_get(:@content);

输出是:

ASDF: #<DTree id: 11,parent_id: nil,content: "bababababa",subsidiary_info: "",deep_info: "blabla",title: "hello",direction: 1,created_at: "2010-10-26 19:27:32",updated_at: "2010-11-01 23:14:31",color: 2,cell_color: 2,howtoinfo: "howtoinfooo",textinfo: "textInfooo",locationinfo: "locationInfoooo",productinfo: "productinfoooo">
TypeError (can't convert nil into String):
    /app/controllers/d_trees_controller.rb:38:in `+'

根据检查,对象似乎没问题,但是instance_variable_get返回一个nil对象

谢谢你的帮助!

解决方法

虽然直接获取这样的实例变量被认为是不好的形式,因为使用attr_accessor是首选方法,这个特定实例中的问题是没有名为@content的实例变量.您所拥有的似乎是ActiveRecord属性.

这些是使用不同的机制获取的:

@d_tree.attributes[:content]

通常这甚至有点多余,因为这将不必要地创建属性哈希的副本.访问的典型方法是:

@d_tree.content

这些值实际上位于ActiveRecord管理的@attributes实例变量中.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读