2017-02-15 109 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