覆盖 Rails 中的属性并获取底层值
对于我的一生,我不知道如何做到这一点。 我有一个模型,其存储值是文件系统上资源的路径。 我希望模型能够从文件系统写入和获取资源,因此我自然希望重写 getter 和 setter 来执行此操作。 那么我如何获取数据库中的基础值?
class MyModel < ActiveRecord::Base
require 'fileutils'
def myThing=(val)
handle = File.open(_____, 'w')
handle.write(val)
end
end
下划线所在的地方是什么? 我见过“write_attribute”用于执行此操作,但它似乎已被弃用。 有任何想法吗? 当然,吸气剂也是如此。
另外,如果我在重写方面提出了错误的观点,我很想听到更好的技术。 唯一不能选择的是将值直接存储在数据库中。
谢谢!
For the life of me, I can't figure out how to do this. I have a model for which the stored value is a path to a resource on the file system. I'd like the model to write and fetch the resource from the file system, so I naturally want to override the getter and setters to do this. How do I then get at the underlying value that's in the db?
class MyModel < ActiveRecord::Base
require 'fileutils'
def myThing=(val)
handle = File.open(_____, 'w')
handle.write(val)
end
end
What goes where the underscores are? I've seen 'write_attribute' used to do this, but it looks to be deprecated. Any ideas? Ditto for the getter, of course.
Also, if I'm barking up the wrong tree regarding overriding, I'd love to hear the better technique. The only thing that's not an option is to store the value directly in the db.
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这应该可以做到:
不过,我会考虑将该列重命名为“my_thing_path”(或 myThingPath,如果必须的话)。
This should do it:
I'd think about renaming the column to "my_thing_path" (or myThingPath, if you must), though.