【发布时间】:2011-03-03 22:56:58
【问题描述】:
所以,我有两个模型,集合和文件夹。
在每个集合中都有一个根文件夹。文件夹都属于一个集合,但也可以相互嵌套。
在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来更新专栏。
标签: ruby-on-rails ruby-on-rails-3 activerecord associations