2009-07-05 32 views
1

我正在使用一個略有奇怪的表命名約定的傳統oracle數據庫,其中每個列名都以表首字母爲前綴,例如policy.poli_id。在生產模式下Rails依賴關係問題

爲了使這個數據庫更容易工作我有一個方法set_column_prefix創建每個列刪除前綴的訪問器。即:

# Taken from wiki.rubyonrails.org/rails/pages/howtouselegacyschemas 
class << ActiveRecord::Base 
    def set_column_prefix(prefix) 
    column_names.each do |name| 
     next if name == primary_key 

     if name[/#{prefix}(.*)/e] 
     a = $1 

     define_method(a.to_sym) do 
      read_attribute(name) 
     end 

     define_method("#{a}=".to_sym) do |value| 
      write_attribute(name, value) 
     end 

     define_method("#{a}?".to_sym) do 
      self.send("#{name}?".to_sym) 
     end 

     end 
    end 
    end 
end 

這是在我的lib /目錄中的文件(insoft.rb),並需要從我到config/environment.rb後的Rails :: Initializer.run塊。

這在發展一直工作正常,但是當我嘗試運行在生產模式下的應用程序,我得到了我的所有車型以下錯誤:

[email protected]:~/code/voyager$ RAILS_ENV=production script/server 
=> Booting Mongrel 
=> Rails 2.3.2 application starting on http://0.0.0.0:3000 
/usr/lib/ruby/gems/1.8/gems/activerecord-2.3.2/lib/active_record/base.rb:1964:in `method_missing': 
undefined method `set_column_prefix' for #<Class:0xb3fb81d8> (NoMethodError) 
    from /home/dgs/code/voyager/app/models/agent.rb:16 

此錯誤是由「配置觸發.cache_classes = true'config/environments/production.rb中的行。 如果我將此設置爲false,那麼rails將啓動,但不會緩存類。我猜這使得軌道緩存所有的模型,然後它運行初始化程序塊

如果我將'require'insoft.rb'「移動到Rails :: Initializer.run塊的開始之前,那麼我得到錯誤,因爲ActiveRecord的尚未初始化:

usr/lib/ruby/gems/1.8/gems/activesupport-2.3.2/lib/active_support/dependencies.rb:443:in `load_missing_constant': uninitialized constant ActiveRecord (NameError) 
    from /usr/lib/ruby/gems/1.8/gems/activesupport-2.3.2/lib/active_support/dependencies.rb:80:in `const_missing' 
    from /usr/lib/ruby/gems/1.8/gems/activesupport-2.3.2/lib/active_support/dependencies.rb:92:in `const_missing' 
    from /home/dgs/code/voyager/lib/insoft.rb:1 

我應該在哪裏進行,包括爲了這個定製的lib和set_column_prefix方法爲它的模型緩存之前有所回升,但畢竟ActiveRecord的文件已加載?

乾杯

戴夫Smylie

回答

2

我應該在哪裏進行,包括爲了這個定製的lib和set_column_prefix方法爲它的模型緩存之前有所回升,但畢竟ActiveRecord的文件已加載?

嘗試設置initializer。你可以用你的猴子補丁的內容稱之爲config/initializers/insoft.rb:

class << ActiveRecord::Base 
    def set_column_prefix(prefix) 
    column_names.each do |name| 
     next if name == primary_key 

     if name[/#{prefix}(.*)/e] 
     a = $1 

     define_method(a.to_sym) do 
      read_attribute(name) 
     end 

     define_method("#{a}=".to_sym) do |value| 
      write_attribute(name, value) 
     end 

     define_method("#{a}?".to_sym) do 
      self.send("#{name}?".to_sym) 
     end 

     end 
    end 
    end 
end 
+0

Thanks guys。這似乎解決了這個問題。 – 2009-07-05 22:35:39