如何访问我覆盖的 Activerecord setter?
我想使用自定义设置器对我的字段进行一些格式化。在 irb 中,如果我像这样测试设置器:
o.field_name = "4"
我看到我的自定义设置器正在被引用。但事实并非如此:
o[:field_name] = "4"
我知道在第一种情况下这是一个函数调用,在第二种情况下我们只是直接设置属性。但我不完全明白如何在不通过我们的自定义设置器的情况下设置该属性,我认为这就是重点。
但我的主要问题是,如果 var 保存我的 field_name,我不知道如何动态引用 a.var 并将其解释为 a.field_name。我所要做的就是a[var],这绕过了我的设置器。
I want to use a custom setter to do some formatting of my fields. In irb if I test the setter like:
o.field_name = "4"
I see that my custom setter is being referred to. But with this it is not:
o[:field_name] = "4"
I understand that in the first case this is a function call and in the second case we are just setting the attribute directly. But I don't completely see how the attribute can be set without going through our custom setter, I thought that was the point.
But my main question is that if var holds my field_name, I don't see how to dynamically refer to a.var and have it be interpreted as a.field_name. All I see to do is a[var] and this bypasses my setter.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
尝试
a.send(var)
wherevar = 'field_name'
这相当于
a.field_name
Try
a.send(var)
wherevar = 'field_name'
That's the equivalent of
a.field_name
o[:field_name] 就像 read_attribute(:field_name) 一样,因此只是读取您所说的值。为了绕过堆栈太深的错误,它在虚拟属性中非常重要。如果你执行[:var],你就得到它的值。虚拟属性是指一个属性,如果您将其值设置为另一个变量,您只是获得它的值,而不是对象。
o[:field_name] is like read_attribute(:field_name), thus is just reads the value as you said. It can be quite important in virtual attributes in order to bypass the stack too deep error. If you do a[:var], you just get its value. A virtual attribute refers to an attribute, if you are setting its value to another variable, you just get its value, not the object.