ActiveRecord中的create/create_record在哪里? [英] Where has create/create_record gone in ActiveRecord?
问题描述
我对ActiveRecord有一个审核猴子补丁,该补丁可在从2.x到4.0.2的所有版本的Rails上使用,但不适用于ActiveRecord 4.1. 4.0的代码如下所示:
I have an audit monkey patch to ActiveRecord that works on all versions of Rails from 2.x to 4.0.2 but does not work with ActiveRecord 4.1. The code for 4.0 looks like this
module HLLAuditStamps
def self.included(base)
# create/update became create_record/update_record in Rails-4.0
base.alias_method_chain :create_record, :audit
base.alias_method_chain :update_record, :audit
private
def create_record_with_audit
set_audit_attributes
. . .
这在4.0.2中有效,但在4.1.2中抛出此异常:
This works in 4.0.2 but throws this exception in 4.1.2:
未定义的方法create_record' for class
ActiveRecord :: Base'(NameError)
undefined method create_record' for class
ActiveRecord::Base' (NameError)
如果我进入rails-4.1.2项目中的rails控制台并在ActivRecord :: Base中列出方法,我会看到:
If I go into rails console in a rails-4.1.2 project and list the methods in ActivRecord::Base I see this:
. . .
- :count_by_sql
- :create
- :create!
- :create_with
- :current_scope
. . .
由于'create'方法在4.0之前很流行,因此使用了原始审核补丁.我回到原始位置,并删除了整个模块中的"_record"段.但是,这只会引发此异常:
As the 'create' method is what was in vogue before 4.0 that was what the original audit patch used. I returned to the original from and removed the '_record' segment throughout the module. However, that simply throws this exception:
undefined method `create' for class `ActiveRecord::Base' (NameError)
那么,在ActiveRecord 4.1中create/create_record到哪里去了?为什么我不能引用显然属于该类的方法?
So, where did create/create_record go to in ActiveRecord 4.1 and why am I unable to reference a method that is evidently part of the that class ?
好吧,它到了这里
#rails / activerecord / lib / active_record.rb
module ActiveRecord
extend ActiveSupport::Autoload
. . .
autoload :Persistence
. . .
所以,现在我只需要弄清楚如何处理这些信息.
So, now I just have to figure out what to do with the information.
推荐答案
See: Does adding a :before_save to an AR model override one already added through a custom extension to AR?
示例:
module HLLAuditStamps
extend ActiveSupport::Concern
included do
before_save :set_audit_attributes
end
private
def set_audit_attributes
. . .
end
end
class ActiveRecord::Base
include HLLAuditStamps
end
这篇关于ActiveRecord中的create/create_record在哪里?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!