DataMapper自引用模型

时间:2015-06-04 21:53:22

标签: ruby sinatra datamapper

我有一个模特:

class Comment
   include DataMapper::Resource
   property :id, Serial
   property :comment, Text, :required => true  
   belongs_to :user
   belongs_to :lecture
   has n, :replies, :child_key => [:source_id]
   has n, :comments, self, :through => :replies, :via => :target
end

我想添加评论作为对另一个已经创建的评论的回复。当我尝试:

lecture = Lecture.get(params[:lecture_id])
comment = Comment.new(:comment => params[:text])  
@user.comments << comment
lecture.comments << comment 

if !params[:parent].nil? then
  parent = Comment.get(params[:parent])
  parent.replies << comment
end

parent.replies << comment行引发错误:
 NoMethodError - undefined method source_id=' for #<Comment @id=nil @comment="asd" @user_id=1 @lecture_id=1>

我的回复模式是:

class Reply 
 include DataMapper::Resource 
  belongs_to :source, 'Comment', :key => true
  belongs_to :target, 'Comment', :key => true
end

如何正确添加评论作为“回复”?感谢。

1 个答案:

答案 0 :(得分:1)

您确定要Reply型号吗?注释树可以仅构建在一个具有自我关联的模型Comment上。

class Comment
  ...
  has n, :replies, 'Comment', :child_key => :source_id
  belongs_to :source, 'Comment', :required => false
end