所以,我有兩個型號,收藏和文件夾。導軌的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不會在使用如社會交往......
任何想法?
你確定'root_folder_id'是由'setup_root_folder'方法設置的嗎?我希望看到一個'save'來更新列。 – zetetic 2011-03-04 01:24:40