2014-09-30 102 views
0

我试图解决updatng记录失败的情况,因为相关集合的id被强制为整数,而id是uuids(to_i在uuid上返回第一个数字部分)。 以下代码片段显示我尝试过的猴子补丁(coment#.map(&:to_i))。尽管该补丁已加载,但访问了原始方法。我可以猴子补丁define_method定义的方法

在ActiveRecord模块中进行更改适用于我,但我宁愿修补冻结rails代码。

我很感激任何提示我失踪。

<!-- language: ruby --> 

module ActiveRecord 
    module Associations 
    module ClassMethods 
     private 
      def collection_accessor_methods(reflection, association_proxy_class, writer = true) 
       collection_reader_method(reflection, association_proxy_class) 

       if writer 
       define_method("#{reflection.name}=") do |new_value| 
        # Loads proxy class instance (defined in collection_reader_method) if not already loaded 
        association = send(reflection.name) 
        association.replace(new_value) 
        association 
       end 

       define_method("#{reflection.name.to_s.singularize}_ids=") do |new_value| 
        ids = (new_value || []).reject { |nid| nid.blank? } #.map(&:to_i) 
        send("#{reflection.name}=", reflection.klass.find(ids).index_by(&:id).values_at(*ids)) 
       end 
       end 
      end 

错误信息是例如

“找不到PosperCategory与ID = 281”

的根本原因是“218”是什么“.MAP(&:to_i”使得原有的UUID的,我需要使用的,因为的UUID。 rails应用程序和一个Java应用程序使用相同的遗留数据库 这在rails 2.2.2中工作,在2.3.2中停止工作,在2.3.3中再次工作(我认为)并且再次停止工作。 .18。升级到rails 3.x对我来说不是一种选择,这里不应该讨论这个问题。

+0

你能后当记录更新失败你得到错误? – thohl 2014-10-01 14:03:01

+0

@thohl我更新了我的问题和错误消息。任何想法? – arcasys 2014-10-17 14:15:43

回答

0

是的,可以在mokey修补中定义动态方法

例如

class Object 
    def methods(*names) 
    names.each do |name| 
     define_method("#{name}=") do |value, &b| 
     puts "setter" 
     puts __method__ 
     end 

     define_method("#{name}") do 
     puts "getter" 
     puts __method__ 
     end 
    end 
    end 
end 

module Module 
    def n_attrib_keys(*names) 
    Object.methods(*names) 
    end 
end 

包括模块类