2010-06-10 20 views

回答

1

你的問題不清楚。 「模型」是指使用ActiveRecord的數據庫支持的模型,對吧?

通常,驗證不是「文件」,而是模型文件中的一系列語句。關係聲明也是如此。

您可以在任意數量的文件中分割模型的內容。該技術根據您是否希望其他文件包含實例方法或類方法而有所不同。

最簡單的是在其他文件中有實例方法。例如

# file foo.rb 
class Foo < ActiveRecord::Base 
    include FooMethods 

    # --- callbacks --- # 
    before_create :record_signup # "before_create" is a "callback". 
    # See http://api.rubyonrails.org/classes/ActiveRecord/Callbacks.html 
    # note that the method could also be from a different class altogether: 
    before_save  EncryptionWrapper.new 
    # See section "Types of callbacks" in the api url referred to above 

    # --- relationships --- # 
    belongs_to :foobar 
    has_many :bars 

    # --- Class Methods --- # 
    def Foo.a_method_name(id) 
    ... 
    end 
end 

~~~~~~~~~~~~~~~~~~~~~~~~~~~ 

# file foo_methods.rb 

module FooMethods 

    def method1 
    ... 
    end 

    def method2 
    ... 
    end 

    private 

    def record_signup # define the callback method 
    self.signed_up_on = Date.today 
    end 
end 

隨口說說,我不如何把回調覆蓋

before_create

在不同的文件比模型的主要類文件。不難弄清楚。但不管放入不同的文件有多容易,我都不會從代碼清晰的角度推薦它。

+0

感謝larry的快速回復.. 我可以在模塊中添加before_validation,after_save,after_create方法嗎?如果我簡單地將該模塊包含在我的課程中,它是否工作?因爲它在一個班級中一起工作。 – 2010-06-10 15:19:58

+0

#文件foo.rb 類Foo <的ActiveRecord :: Base的 包括FooMethods #--- ---關係# belongs_to的:foobar的 的has_many:酒吧 #---類方法---# 高清Foo.a_method_name(ID) ... 結束 結束 ~~~~~~~~~~~~~~~~~~~~~~~~~~~ #文件foo_methods.rb module FooMethods def method1 ... end def method2 ... end end 這就是我想要的完美解決方案。但我有另一個問題是。 加載有沒有什麼特別的優勢?如果我們將維護另一個模塊中的實例方法。 – 2010-06-10 15:38:12

+0

@krunal,你的評論是行包裝和不可讀的。我建議你將它添加到你的原始q之前的「添加」或一些這樣的。 此外,請記住upvote是有用的答案,並標記爲「回答」解決您的問題。 回覆:加載:如果有多個源文件對你有幫助,沒有什麼重要的區別。 回覆:before_validation等,看到更新的答案 – 2010-06-10 19:45:17