#コメント機能を実装してみる
##アプリケーションを作成
ターミナル
% cd projects
% rails _6.0.0_ new mini_talk_app -d mysql
% cd mini_talk_app
% rails db:create
##コントローラーとモデルを作成
ターミナル
% rails g controller messages new
% rails g model message text:text
% rails db:migrate
##ルーティングを設定
app/config/routes.rb
Rails.application.routes.draw do
root 'messages#new'
resources :messages, only: [:create]
end
##messages_controller.rbを編集
new.html.erbを編集
<h3>mini_talk_app</h3>
<%= form_with model: @message do |f| %>
<%= f.text_field :text %>
<%= f.submit '送信' %>
<% end %>
<div id='messages'>
<% @messages.reverse_each do |message| %>
<p><%= message.text %></p>
<% end %>
</div>
##チャネルを作成
ターミナル
% rails g channel message
##stream_fromを追加
app/channel/message_channel.rb
class MessageChannel < ApplicationCable::Channel
def subscribed
stream_from "message_channel"
end
def unsubscribed
# Any cleanup needed when channel is unsubscribed
end
end
##messages_controller.rbを編集
app/controller/messages_controller.rbclass MessagesController < ApplicationController
def new
@messages = Message.all
@message = Message.new
end
def create
@message = Message.new(text: params[:message][:text])
if @message.save
ActionCable.server.broadcast 'message_channel', content: @message
end
end
end
##message_channel.jsを編集
app/javascript/channels/message_channel.js
import consumer from "./consumer"
consumer.subscriptions.create("MessageChannel", {
connected() {
// Called when the subscription is ready for use on the server
},
disconnected() {
// Called when the subscription has been terminated by the server
},
received(data) {
const html = `<p>${data.content.text}</p>`;
const messages = document.getElementById('messages');
const newMessage = document.getElementById('message_text');
messages.insertAdjacentHTML('afterbegin', html);
newMessage.value='';
}
});
#以上!