如何将 ActiveRecord 属性辅助方法添加到虚拟属性?

编程入门 行业动态 更新时间:2024-10-28 01:18:23
本文介绍了如何将 ActiveRecord 属性辅助方法添加到虚拟属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

ActiveRecord 提供属性辅助方法,例如 _? 和脏"方法(_changed? 等)

ActiveRecord offers attribute helper methods such as _? and the "dirty" methods (_changed? etc.)

是否有 Rails 方法可以在非持久化或虚拟"属性上定义这些相同的方法?

Is there a Rails way to define these same methods on non-persisted or "virtual" attributes?

我希望是这样的:

class MyClass < ActiveRecord::Base some_macro :my_attribute end $ @my_class = MyClass.new $ @my_class.my_attribute? # => false $ @my_class.my_attribute_changed? # => false

推荐答案

好吧,这确实是值得研究的有趣事情.显然没有直接的方法可以做到这一点......我发现了两件事

Well this was certainly something interesting to investigate. Apparently there is not a straight forward way to do this... here are two things I found

从 2009 年起

从 2011 年开始 - 加强了 2009 年的帖子但让它更干净一点.您创建一个更新属性哈希的模块.来自 Brandon Weiss 的帖子:

From 2011 - reinforces the 2009 post but makes it a bit cleaner. You create a module that updates the attribute hash. From the Brandon Weiss post:

# app/models/dirty_associations.rb module DirtyAssociations attr_accessor :dirty def make_dirty(record) self.dirty = true end def changed? dirty || super end end # app/models/lolrus.rb class Lolrus include DirtyAssociations has_and_belongs_to_many :buckets, :after_add => :make_dirty, :after_remove => :make_dirty end

还有这个插件 此处提到,但我不确定它对您有多大用处.

There is also this plugin mentioned here but I am not sure how useful it is for you.

更多推荐

如何将 ActiveRecord 属性辅助方法添加到虚拟属性?

本文发布于:2023-07-17 10:44:34,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1132394.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:属性   如何将   方法   ActiveRecord

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!