0

我一直在設計模式之間跳躍,首先嚐試多態,現在登陸STI。主要目標是實現服務器>主機>訪客模式,其中服務器具有主機,主機具有訪客並且每個都能夠具有帖子。雖然這不是問題的主要目的,但設計問題中的任何想法都會有所幫助,因爲這是我的第一個rails或ruby項目。Rails 4路由單表繼承和自引用

我現在擁有的是:

class Device 
    has_may :children, :class_name => "Device", :foreign_key => "parent_id" 
    belongs_to :parent, :class_name => "Device" 

    has_many :posts 
end 

class Server,Host,Guest < Device 
end 

STI的使用,因爲服務器,主機,客戶基本上具有相同的屬性。

我在設置路由和控制器時遇到問題,所以我可以查看服務器的子類型爲Host或創建新服務器的主機。

回答

0

首先,好東西是添加下面的東西,使一切更容易地使用你:

class Device < ActiveRecord::Base 
    has_many :children, :class_name => "Device", :foreign_key => "parent_id" 
    has_many :servers, -> { where type: "Server" }, :class_name => "Device", :foreign_key => "parent_id" 
    has_many :hosts, -> { where type: "Host" }, :class_name => "Device", :foreign_key => "parent_id" 
    has_many :guests, -> { where type: "Guest" }, :class_name => "Device", :foreign_key => "parent_id" 
    belongs_to :parent, :class_name => "Device" 

    has_many :posts 
end 

有了這一點,你就可以做server.hosts等,這是相當方便。

然後,由於Rails加載系統,您應該將每個子類(Server,Host,Guest)移動到它自己的文件中。您可以嘗試訪問控制檯中的模型服務器,您將收到一個未定義的錯誤。要修復它,你需要加載模型Device,或者直接將每個子類移動到不同的文件中。

最後,對於路由/控制器部分,我會建議你閱讀我寫的有關STI資源的通用控制器的文章:http://samurails.com/tutorial/single-table-inheritance-with-rails-4-part-2/

請注意,這是第二部分,更多詳細信息請查看其他文章。