在钢轨一个ActiveRecord对象跟踪脏不持久化属性 [英] Track dirty for not-persisted attribute in an ActiveRecord object in rails

查看:128
本文介绍了在钢轨一个ActiveRecord对象跟踪脏不持久化属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个对象,它继承自ActiveRecord的,但它有没有在DB坚持一个属性,如:

I have an object that inherits from ActiveRecord, yet it has an attribute that is not persisted in the DB, like:

 class Foo < ActiveRecord::Base
   attr_accessor :bar
 end

我希望能够跟踪更改为巴,用类似bar_changed?',通过加载ActiveModel脏提供的方法。问题是,当我尝试实现这个肮脏的对象上,如文档描述,我m到处是错误,因为这两种ActiveRecord的和加载ActiveModel定义 define_attribute_methods ,但具有不同数量的参数,所以我尝试调用时收到错误 define_attribute_methods [:巴]

I would like to be able to track changes to 'bar', with methods like 'bar_changed?', as provided by ActiveModel Dirty. The problem is that when I try to implement Dirty on this object, as described in the docs, I'm getting an error as both ActiveRecord and ActiveModel have defined define_attribute_methods, but with different number of parameters, so I'm getting an error when trying to invoke define_attribute_methods [:bar].

我试图混淆 define_attribute_methods 包括前加载ActiveModel ::肮脏,但没有运气:我得到一个不定义的方法错误。

I have tried aliasing define_attribute_methods before including ActiveModel::Dirty, but with no luck: I get a not defined method error.

在如何处理这个任何想法?当然,我可以手动编写所需的方法,但我想知道是否有可能使用Rails模块来做,通过扩展加载ActiveModel功能不是由ActiveRecord的处理属性。

Any ideas on how to deal with this? Of course I could write the required methods manually, but I was wondering if it was possible to do using Rails modules, by extending ActiveModel functionality to attributes not handled by ActiveRecord.

推荐答案

我使用了 attribute_will_change!方法和事情似乎是工作的罚款。

I'm using the attribute_will_change! method and things seem to be working fine.

这是在 active_model / dirty.rb 定义的私有方法,但是ActiveRecord的所有模型中混合了。

It's a private method defined in active_model/dirty.rb, but ActiveRecord mixes it in all models.

这是我最终实现在我的模型类:

This is what I ended up implementing in my model class:

def bar
  @bar ||= init_bar
end
def bar=(value)
  attribute_will_change!('bar') if bar != value
  @bar = value
end
def bar_changed?
  changed.include?('bar')
end

init_bar 法只是用来初始化属性。你可能会或可能不需要它。

The init_bar method is just used to initialise the attribute. You may or may not need it.

我并不需要指定任何其他方法(如 define_attribute_methods )或包含的任何模块。 你必须重新实现一些自己的方法,但至少的行为将与加载ActiveModel大多是一致的。

I didn't need to specify any other method (such as define_attribute_methods) or include any modules. You do have to reimplement some of the methods yourself, but at least the behaviour will be mostly consistent with ActiveModel.

我承认我没有测试它彻底呢,但到目前为止,我所遇到的任何问题。

I admit I haven't tested it thoroughly yet, but so far I've encountered no issues.

这篇关于在钢轨一个ActiveRecord对象跟踪脏不持久化属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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