2011-03-03 66 views
2

所以,我有兩個型號,收藏和文件夾。導軌的has_many/HAS_ONE同型號

在每個系列有一個根文件夾。文件夾都屬於一個集合,但也可以嵌套在一起。

this question,我寫我的模型如下圖所示。我還添加了一個回調函數,因爲我總是想要一個Collection開始使用根文件夾。

class Folder < ActiveRecord::Base 
    has_one :master_collection, :class_name => 'Collection', :foreign_key => :root_folder_id 
    belongs_to :collection 
    belongs_to :parent, :class_name => 'Folder' 
    has_many :subfolders, :class_name => 'Folder', :foreign_key => :parent_id 
    ... 
end 

class Collection < ActiveRecord::Base 
    belongs_to :root_folder, :class_name => 'Folder' 
    has_many :folders 

    after_create :setup_root_folder 

    private 
    def setup_root_folder 
    self.root_folder = Folder.create(:name => 'Collection Root', :collection => self) 
    end 
end 

在文件夾中我有列:PARENT_ID,folder_id 在收藏我有柱:root_folder_id

這看起來像它應該工作,但我在控制檯中這種奇怪的行爲:

ruby-1.9.2-p0 :001 > c = Collection.create(:name=>"Example") 
=> #<Collection id: 6, name: "Example", ...timestamps..., root_folder_id: 8> 
ruby-1.9.2-p0 :003 > f = c.root_folder 
=> #<Folder id: 8, parent_id: nil, name: "Collection Root", ...timestamps..., collection_id: 6> 
ruby-1.9.2-p0 :004 > f.master_collection 
=> nil 

因此,顯然該關聯在集合端工作,但根文件夾無法找到它作爲根的集合,即使外鍵可用且ActiveRecord不會在使用如社會交往......

任何想法?

+0

你確定'root_folder_id'是由'setup_root_folder'方法設置的嗎?我希望看到一個'save'來更新列。 – zetetic 2011-03-04 01:24:40

回答

2

我懷疑這是發生了什麼事:

  1. 創建類集c
  2. C被保存到數據庫中
  3. Rails的要求C.after_create
  4. 創建文件夾˚F
  5. F被保存到數據庫
  6. C'S root_folder_id設爲F的id
  7. 這種變化是不是保存到數據庫
  8. 你叫F.master_collection
  9. ˚F查詢數據庫,尋找與集合coleections.root_folder_id = folders.id
  10. 由於C的新root_folder_id尚未保存,F未找到什麼

如果你要測試的這款,叫c.save在你的示例代碼調用f.master_collection前 - 你應該得到的集合,就像你希望(你MIG也需要f.reload)。

這麼說,我從來不喜歡雙belongs_to S(文件夾belongs_to的收藏+收藏belongs_to的ROOT_FOLDER)。相反,我會推薦:

class Collection < ActiveRecord::Base 
    has_one :root_folder, :class_name => 'Folder', :conditions => {:parent_id => nil} 

    # ...other stuff... 
end 

希望幫助!

PS:如果從根文件夾把它叫做你的Folder.master_collection定義只會給你回的集合 - 所有其他文件夾都將直接返回零,因爲沒有收藏有root_folder_id s表示指向他們。這是你的意圖嗎?

+0

RE:master_collection只適用於根文件夾,這就是我的意圖。仍在處理您的其他答案,謝謝! – Andrew 2011-03-04 02:09:39

+0

@Andrew一切順利,然後 - 只是檢查。乾杯! – 2011-03-04 02:12:40

+0

RE:'has_one:root_folder ....:conditions {:parent_id => nil}'。可以有多個集合,每個集合都有一個根文件夾。 ActiveRecord如何知道具有nil parent_id的文件夾屬於哪個集合? – Andrew 2011-03-04 02:24:09