[英]Rails has_many / has_one same model
所以,我有两个模型,集合和文件夹。
每个集合中都有一个根文件夹。 文件夹都属于一个集合,但也可以相互嵌套。
在这个问题之后,我写了我的模型,如下所示。 我还添加了一个回调,因为我总是希望 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.after_create
root_folder_id
设置为 F 的id
F.master_collection
coleections.root_folder_id = folders.id
Collectionsroot_folder_id
还没有保存,F 什么也没找到如果你想测试,通话c.save
在你的示例代码调用之前f.master_collection
-你应该得到的集合,就像你希望(你可能需要一个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
定义只会给你一个集合 - 所有其他文件夹只会返回 nil,因为没有集合具有指向它们的root_folder_id
s。 这就是你的意图吗?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.