LoginSignup
0
0

More than 3 years have passed since last update.

コメント機能の実装要点メモ

Posted at

はじめに

投稿に対して非同期通信でコメントできるようにする機能についてのメモ書きです。

前提

Ruby 2.6.5p114
Rails 6.0.3.4
macOS Catalina

ルーティングの修正

config/routes
  resources :items do
    resources :orders, only: [:index, :create]
    resources :comments, only: [:create]
  end

コメントの削除機能は実装しないため、destroyアクションは不要です。

チャネルの作成

ターミナル
% rails g channel comment

createアクションの設定

app/controllers/comments_controller
  def create
    @comment = Comment.new(comment_params)
    if @comment.save
      @user = @comment.user
      ActionCable.server.broadcast 'comment_channel', comment: [@comment, @user]
    end
  end

ActionCableの記述でbroadcastを通してcomment_channelに向けて@commentを送信しています。送信された情報はcomment_channel.jsで受け取り、テンプレートリテラルにする必要があります。

単体テストコード

contentが存在すれば保存できること、contentが存在しない場合保存できないこと、userと紐づいていない場合保存できないこと、itemと紐づいていない場合保存できないことをテストします。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0