Tim*_*Tim 0 ruby recursion datamapper sinatra
我正在使用DataMapper和Sinatra构建一个小型Ruby应用程序,我正在尝试定义一个基本的博客模型:
由于每个评论belongs_to帖子的事实,我很难在评论之间找到自我参照关系.我的课程现在看起来像这样:
class User
include DataMapper::Resource
property :id, Serial
property :username, String
property :password, String
has n, :post
endRun Code Online (Sandbox Code Playgroud)
class Post
include DataMapper::Resource
property :id, Serial
property :content, Text
belongs_to :user
has n, :comment
endRun Code Online (Sandbox Code Playgroud)
class Comment
include DataMapper::Resource
property :id, Serial
property :content, Text
belongs_to :user
belongs_to :post
endRun Code Online (Sandbox Code Playgroud)
我正在关注协会的指南并构建一个新对象(CommentConnection)以将两个注释链接在一起,但我的问题是每个子注释不应属于Comment类隐含的Post.
我的第一直觉是为Comments提取一个超类,这样一个子类可以是"顶级"并属于一个帖子,而另一种类型的注释属于另一个注释.不幸的是,当我这样做时,我遇到的问题是注释ID变为空.
在DataMapper中建模这种递归注释关系的最佳方法是什么?
您需要的是注释中的自引用连接,例如,每个注释都可以有父注释.请尝试以下方法:
class Comment
include DataMapper::Resource
property :id, Serial
property :content, Text
has n, :replies, :child_key => [ :original_id ]
belongs_to :original, self, :required => false #Top level comments have none.
belongs_to :user
belongs_to :post
end
Run Code Online (Sandbox Code Playgroud)
这将允许您对任何给定的注释进行回复,但是如果音量变高,访问它们可能会有点讨厌(慢).如果你得到这个工作并想要更复杂的东西,你可以看看嵌套集,我相信有一个嵌套的插件用于DataMapper,但我没有使用过.