为什么在执行 record.inspect 时不会输出 attr_accessor 虚拟属性 [英] Why do attr_accessor virtual attributes not get outputted when you do record.inspect

查看:35
本文介绍了为什么在执行 record.inspect 时不会输出 attr_accessor 虚拟属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的 ListItem rails 模型中:

In my ListItem rails model I have:

attr_accessor :catalyst_action, :actor_user_id, :actor_full_name

我可以在控制器中设置这些变量,并且我确认当记录到达观察者时它们仍然存在.

I'm able to set these variables in the controller and I confirmed that when the record gets to the observer they are still there.

控制器

  @list_item.actor_user_id = current_user.id
  @list_item.actor_full_name = current_user.full_name
  @list_item.save

观察者

  Rails.logger.info '@list_item.inspect - ListItemObserver'
  Rails.logger.info record.inspect
  Rails.logger.info record.actor_user_id
  Rails.logger.info record.actor_full_name
  Rails.logger.info '@list_item.inspect - ListItemObserver'

这些输出很好,但是当我执行 record.inspect 时,虚拟属性没有被输出,但是如果我专门记录它们,它们就在那里并输出.为什么输出记录不包含 vattr?如何获取记录以包含这些变量?

These output just fine, but when I do the record.inspect the virtual attr are not being outputted, but if I log them specifically they are there and output. Why does outputting record not include the vattr? How can I get record to include these variables?

谢谢

推荐答案

它们是虚拟属性,而不是真实属性.Active Record 提供了 inspect 方法(定义在这里),它遍历模型的所有列,这些列显然不包括虚拟属性.

They are virtual attributes, not real attributes. Active Record provides the inspect method (definition is here) and it iterates through all the columns of the model which obviously don't include the virtual attributes.

如果您想了解模型上的虚拟属性是什么,那么没有简单的方法可以做到.您必须将它们分配到某个列表中,然后从该列表中读取.

If you want to find out what the virtual attributes are on the model then there's no easy way to do that. You would have to assign them into a list somewhere and then read from that list.

这篇关于为什么在执行 record.inspect 时不会输出 attr_accessor 虚拟属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆