2017-02-15 97 views
0

我想实现评论回复功能到我的项目,但我不是很确定我使用的方法。我的基本想法是将所有的评论保留在一张表中,同时有另一个表comments_replies这将有父母的评论(评论)和评论(回复)。现在我有这样的事情是comments_replies迁移:在同一张表中有一张表有两个外键rails

模型comments_reply.rb

belongs_to :comment, class_name: 'Comment' 

,并在模型comment.rb

create_table :comments_replies do |t| 
    t.integer :parent_comment_id, index: true, foreign_key_column_for: :comments, null: false 
    t.integer :reply_comment_id, index: true, foreign_key_column_for: :comments, null: false 
    t.timestamps null: false 
end 

has_many :comments_replies, foreign_key: :parent_comment_id, foreign_key: :reply_comment_id 

对于第二部分,因为即时尝试使用RSPEC用于测试目的,在模型comments_reply_spec.rb我有:

require 'rails_helper' 

RSpec.describe CommentsReply, type: :model do 
    let(:comments_reply) { create(:comments_reply) } 
    subject { comments_reply } 

    it { is_expected.to respond_to(:parent_comment_id) } 
    it { is_expected.to respond_to(:reply_comment_id) } 
end 

,但我不知道如何正确地测试这种情况下,因此任何建议,将不胜感激

回答

1

你所想达到可以从“注释”本身模型来完成。你只需要在“评论”中的另一列“parent_id”,它将引用同一个表中的父级注释。对于所有那些主要的“评论”(不回复任何评论)列'parent_id'将为空。

所以你的模型看起来像下面

class Comment 
    belongs_to :parent_comment, foreign_key: :parent_comment_id, class_name: 'Comment' 
    has_many :replies, foreign_key: :parent_comment_id, class_name: 'Comment' 
end 

根据您目前的做法

你有两个foreign_key这是不对的指定关联。在你的“评论”模式中,你需要关联。 1)评论的所有回复2)获取家长评论。

has_many :comments_replies, foreign_key: :parent_comment_id 
has_many :replies, through: :comment_replies 

has_one :parent_comment_reply, foreign_key: :reply_comment_id, class_name: 'CommentReply' 
has_one :parent_comment, through: :parent_comment_reply 

而且在CommentReply模型

belongs_to :parent_comment, foreign_key: :parent_comment_id, class_name: 'Comment' 
belongs_to :reply_comment, foreign_key: :reply_comment_id, class_name: 'Comment' 

您的规格看起来像下面

require 'rails_helper' 

RSpec.describe CommentsReply, type: :model do 
    let(:parent_comment){ create(:comment) } 
    let(:child_comment) { create(:comment) } 

    let(:comment_reply) { create(:comment_reply, parent_comment_id: parent_comment.id, reply_comment_id: child_comment.id) } 

    subject { comment_reply } 

    it { is_expected.to respond_to(:parent_comment_id) } 
    it { is_expected.to respond_to(:reply_comment_id) } 

    it "should correctly identify the parent/child relationship" do 
    expect(comment_reply.reply_comment.id).to be_eql(child_comment.id) 
    expect(comment_reply.parent_comment.id).to be_eql(parent_comment.id) 
    end 

end 
+0

我错过了建议的方法,我相信它会更容易和更加有用,但是应该如何我在迁移和模型中指定parent_id字段,是否可以简单地在迁移中写入: t.integer:parent_id,index:true,foreign_key_column_for :::comments,null:false 评论模型: belongs_to:comment,foreign_key::parent_id,class_name:'Comment' 还有一件事,在评论模型中,我需要写一些类似于: has_many:comments,foreign_key :: parent_id – Hatik