如何将 ActiveRecord 属性辅助方法添加到虚拟属性? [英] How can I add ActiveRecord attribute helper methods to virtual attributes?

查看:33
本文介绍了如何将 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 属性辅助方法添加到虚拟属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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