导轨的has_many/HAS_ONE同型号
问题描述:
所以,我有两个型号,收藏和文件夹。导轨的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不会在使用如社会交往......
任何想法?
答
我怀疑这是发生了什么事:
- 创建类集c
- C被保存到数据库中
- Rails的要求
C.after_create
- 创建文件夹˚F
- F被保存到数据库
- C'S
root_folder_id
设为F的id
- 这种变化是不是保存到数据库
- 你叫
F.master_collection
- ˚F查询数据库,寻找与集合
coleections.root_folder_id = folders.id
- 由于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表示指向他们。这是你的意图吗?
你确定'root_folder_id'是由'setup_root_folder'方法设置的吗?我希望看到一个'save'来更新列。 – zetetic 2011-03-04 01:24:40