所以,我有两个型号,收藏和文件夹。导轨的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