2015-06-04 69 views
0

我有一個模型: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

您確定要Reply型號嗎?評論樹可以建立在只有一個自我關聯的模型Comment上。

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

這是行得通的!謝謝 – user1576633