Terminal
% cd projects
% rails _6.0.0_ new mini_talk_app -d mysql
% cd mini_talk_app
% rails db:create
Terminal
% 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
app/controllers/messages_controller.rb
class MessagesController < ApplicationController
def new
@messages = Message.all
@message = Message.new
end
def create
@message = Message.new(text: params[:message][:text])
end
end
java:app/views/messages/new.html.erb
<h3>mini_talk_app</h3>
<%= form_with model: @message do |f| %>
<%= f.text_field :text %>
<%= f.submit 'Send' %>
<% end %>
<div id='messages'>
<% @messages.reverse_each do |message| %>
<p><%= message.text %></p>
<% end %>
</div>
Terminal
% rails g channel message
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
app/controller/messages_controller.rb
class 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
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='';
}
});
Recommended Posts