覆盖 Rails 中的属性并获取底层值

发布于 2024-07-18 08:39:39 字数 466 浏览 4 评论 0原文

对于我的一生,我不知道如何做到这一点。 我有一个模型,其存储值是文件系统上资源的路径。 我希望模型能够从文件系统写入和获取资源,因此我自然希望重写 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

尐籹人 2024-07-25 08:39:39

这应该可以做到:

handle = File.open(attributes["myThing"]) 

不过,我会考虑将该列重命名为“my_thing_path”(或 myThingPath,如果必须的话)。

This should do it:

handle = File.open(attributes["myThing"]) 

I'd think about renaming the column to "my_thing_path" (or myThingPath, if you must), though.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文