2012-04-23 65 views
3

我使用軌道3.2.3與超過100個模型。問題是目錄應用程序/模型太擁擠。我把目錄分成幾個組,並添加autoload_paths(用於新的子目錄)。我不希望我的模型使用名稱空間,因爲它最終會變成幾個不利於開發的名稱空間。 比方說:如何避免命名空間activerecord模型?

# app/models/listing.rb 
class Listing < ActiveRecord::Base 
    has_many :communications 
end 

# app/models/listing/communication.rb 
class Communication < ActiveRecord::Base 
end 

在我的Rails控制檯,它的工作原理與絕對引用任何車型除了在ActiveRecord關聯。我無法致電Listing.first.communications。我看到它正在嘗試加載Listing :: Communication,它失敗了,因爲這個文件的內容是Communication(沒有命名空間)。

LoadError: Expected /home/chamnap/my_app/app/models/listing/communication.rb to define Listing::Communication 

有沒有一種方法可以將模型分組到目錄中,並在沒有命名空間的情況下使用它們?或者是否有預加載所有模型的方法,以便Rails不會在運行中加載模型?

回答

5

Rails 3中的子目錄和關聯模型存在問題。我也偶然發現了這一點。

我的解決辦法是指向一個明確的:CLASS_NAME爲每個協會在子目錄模型,如

class Listing < ActiveRecord::Base 
    has_many :communications, :class_name => "::Communication" 
end 

使用採取通知「::」以前型號名稱 - 它的軌道說沒有通信模型的命名空間。

+0

啊,非常感謝。我檢查了activerecord,並看到它如何加載關聯(使用compute_type),但我忘記了這一點。我瀏覽了一些博客,它說這是一種默認行爲。 – Chamnap 2012-04-23 14:56:57

2
# e.g. subscription/coupon defines ::Coupon, would would blow up with expected coupon.rb to define Subscription::Coupon 
# to remove this: 
# a: namespace the models 
# b: move them to top-level 
# c: add :class_name => "::Coupon" to all places where they are used as associations 
ActiveRecord::Reflection::MacroReflection.class_eval do 
    def class_name_with_top_level 
    "::#{class_name_without_top_level}".sub("::::","::") 
    end 
    alias_method_chain :class_name, :top_level 
end