实现ActiveModel Dirty Rails的问题3.2.8

我想检查模型上的属性何时发生了变化。 我试图检查值!=在执行保存之前表单上的值但该代码实际上很难看并且有时不能正常工作。 与使用update_column相同,update_column不在我的模型类中进行validation。 如果我在不做其他事情的情况下使用update_attributes,我将无法检查何时根据我的理解更新字段。 从我对Stack Overflow和其他网站的网络研究看来,使用ActiveModel Dirty是可行的方法。

我看过这个: http : //api.rubyonrails.org/classes/ActiveModel/Dirty.html

我希望在使用update_attributes之后使用它来检查模型上是否更改了布尔标志。 我尝试按照附带链接中的描述进行最小化实施。 我在ActiveRecord类中添加了以下内容:

include ActiveModel::Dirty define_attribute_methods [:admin] 

我尝试添加我想要跟踪的三个属性。 我从一个属性开始,看看我是否能让它工作。 我运行rspec测试时收到以下错误。 一旦我删除了论点,我就没有错误。

 Exception encountered: # 

删除参数后,我决定使用admin而不是name在我的模型中包含类似的方法。 其他Rspec测试打破了save方法。 但是我觉得问题在于我如何实现ActiveModel Dirty。

我已阅读其他Stack Overflowpost,其中评论者表示这已包含在3.2.8中,因此我从3.2.6升级到3.2.8。 我不明白这是什么意思所以在得到错误之后我决定离开include ActiveModel :: Dirty语句并尝试使用admin_changed? 当然它没有用。

除了我在这里提供的链接之外,我还没有找到任何关于如何为此设置的内容。 我发现的所有其他研究都假定初始设置是正确的,并且更新到当前稳定版本的Rails会解决他们的问题。

任何帮助将不胜感激如何实现这一点。 执行链接中所述的最小实现是行不通的。 也许还有其他我想念的东西。

问题似乎是ActiveRecord重新定义了define_attribute_methods方法以接受0个参数(因为ActiveRecord自动为数据库表中的每一列创建属性方法): https : //github.com/rails/rails/blob/master/activerecord/lib /active_record/attribute_methods.rb#L23

这将覆盖ActiveModel提供的define_attribute_methods方法: https : //github.com/rails/rails/blob/master/activemodel/lib/active_model/attribute_methods.rb#L240

解:

我想出了一个对我有用的解决方案……

将此文件另存为lib/active_record/nonpersisted_attribute_methods.rb : https : lib/active_record/nonpersisted_attribute_methods.rb

然后你可以做这样的事情:

 require 'active_record/nonpersisted_attribute_methods' class Foo < ActiveRecord::Base include ActiveRecord::NonPersistedAttributeMethods define_nonpersisted_attribute_methods [:bar] end foo = Foo.new foo.bar = 3 foo.bar_changed? # => true foo.bar_was # => nil foo.bar_change # => [nil, 3] foo.changes[:bar] # => [nil, 3] 

但是,当我们这样做时,看起来我们会收到警告:

 DEPRECATION WARNING: You're trying to create an attribute `bar'. Writing arbitrary attributes on a model is deprecated. Please just use `attr_writer` etc. 

因此我不知道这种方法在Rails 4中是否会破坏或更难…

也可以看看:

尝试添加add =,如下所示:

 define_attribute_methods = [:admin] 

这种变化对我有用。 不确定它是否与此有关 ?