【问题标题】:ruby on rails add functionality to model property changeruby on rails 添加功能以更改模型属性
【发布时间】:2009-12-15 00:53:53
【问题描述】:

在我的rails 模型中,我有一个名为employer_wcb 的小数属性。如果在更改雇主 wcb 时将脏位设置为 true,我希望它。我想覆盖employer_wcb setter 方法。有什么办法(特别是使用元编程)?

【问题讨论】:

    标签: ruby-on-rails ruby metaprogramming alias-method


    【解决方案1】:

    实际上,从 Rails v2.1 开始,这已被融入到 Rails 中。看看documentation for ActiveRecord::Dirty。总结:

    # Create a new Thing model instance;
    # Dirty bit should be unset...
    t = Thing.new
    t.changed?              # => false
    t.employer_wcb_changed? # => false
    
    # Now set the attribute and note the dirty bits.
    t.employer_wcb = 0.525
    t.changed?              # => true
    t.employer_wcb_changed? # => true
    t.id_changed?           # => false
    
    # The dirty bit goes away when you save changes.
    t.save
    t.changed?              # => false
    t.employer_wcb_changed? # => false
    

    【讨论】:

    • 当然。但是有两个警告:我们不知道哪个版本的 Rails 是针对的(不太可能是一个问题,但是嘿!)而且我不相信 ActiveRecord::Dirty 跟踪虚拟属性。提问者没有具体说明employer_wcb 的性质。
    • +1 - @Daniel:如果您使用 > 2.1 并且employer_wcb 不是虚拟属性,这是接受的最佳答案。
    • ActiveRecord::Dirty 在被 2.1 接受之前是一个插件。 code.bitsweat.net/svn/dirty
    【解决方案2】:

    如果您不想使用 rail 内置的脏位功能(比如说您出于其他原因想要覆盖),则不能使用别名方法(请参阅上面史蒂夫条目中的我的 cmets)。但是,您可以使用对 super 的调用来使其工作。

      def employer_wcb=(val)
        # Set the dirty bit to true
        dirty = true
        super val
      end
    

    这很好用。

    【讨论】:

    • 不错!这比 alias 优雅多了!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-14
    • 1970-01-01
    • 2011-10-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多