2016-03-17 40 views
0

在Rails中,我創建了一個新表格。當調用「ActiveRecord :: Base.create」時,如何調用「create」?

class Post < ActiveRecord::Base 
end 

然後我創建新的記錄。當致電Post.create時,create是在persistance.rb中定義的方法。

Post.method(:create).source_location 
=> #["D:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/activerecord-4.2.5.2/lib/active_record/persistence.rb", 29] 

Basebase.rb被定義在相同的目錄中。

說看到文件,模塊Persistance和類Base是在ActiveRecord相同的水平。

那麼如何才能Post電話create

回答

3

你需要經典的分層繼承和平行繼承之間分開。

在Ruby類中只能從一個類繼承,但它們可以包含很多模塊。這就是通常所說的其他語言中的mixin或traits。

module A 
    def hello(name = "World") 
    "Hello #{name}" 
    end 
end 

module B 
    def goodbye(name = "World")) 
    "Goodbye #{name}" 
    end 
end 

class Base 
    include A 
    include B 
end 

class Foo < Base 
end 

foo = Foo.new 
puts foo.hello # => Hello World 
puts foo.goodbye # => Goodbye World 

在這種情況下ActiveRecord::Base包括許多模塊,例如ActiveRecord::Persistence其提供其功能。

您也混淆了名稱空間和繼承的概念。 Ruby沒有實際的命名空間(有自己的關鍵字),但你可以通過將它們放置在一個模塊中封裝了大多數類型的對象:

module Foo 
    class Bar 
    end 

    module Baz 
    class Bar 
    end 
    end 
end 

這不會影響繼承。例如在這種情況下,Foo::BarFoo::Baz::Bar之間沒有實際的連接。在定義類或模塊的文件與繼承樹的工作方式之間也沒有直接關係。 Ruby會高興地讓你把所有東西都塞進一個文件中。

+0

關於什麼的意見? – max

+0

對不起。我認爲Rails的工作原理如下。 '模塊的ActiveRecord 模塊持久 模塊類方法 \t DEF創建 端 端 端 類基地 包括持久性 端 端 類郵 Messi

+0

他們看起來不太好,我不能插入'\ n'。 – Messi

相關問題