2011-03-03 67 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