👌
chat機能に通知機能を持たせる2
chatコントローラー
class Public::ChatsController < ApplicationController
before_action :authenticate_user!
before_action :set_user_and_room, only: [:show]
def show
@chats = @room.chats
@chat = Chat.new(room_id: @room.id)
end
def create
@chat = current_user.chats.new(chat_params)
@chat.save
end
private
def set_user_and_room
@user = User.find(params[:user_id])
@room = find_or_create_room
end
def find_or_create_room
rooms = current_user.user_rooms.pluck(:room_id)
user_room = UserRoom.find_by(user_id: @user.id, room_id: rooms)
return user_room.room if user_room
create_new_room
end
def create_new_room
room = Room.create
UserRoom.create(user_id: @user.id, room_id: room.id)
UserRoom.create(user_id: current_user.id, room_id: room.id)
room
end
def chat_params
params.require(:chat).permit(:message, :room_id)
end
end
show.html.erb
<div class="container">
<div class="row">
<div class="col-xs-6">
<h2>CHAT ROOM </h2>
<table class="table">
<thead>
<tr>
<th style="text-align: left; font-size: 20px;"><%= current_user.username %></th>
<th style="text-align: right; font-size: 20px;"><%= @user.username %></th>
</tr>
</thead>
<tbody id="messages">
<% @chats.each do |chat| %>
<%= render 'message', chat: chat %>
<% end %>
</tbody>
</table>
<%= form_with model: @chat, url: public_user_chats_path, local: false do |f| %>
<div class="arrow_box">
<%= f.text_field :message %>
</div>
<%= f.hidden_field :room_id %>
<button type="submit" class="btn btn-sm btn-success chat-btn">SEND</button>
<% end %>
</div>
</div>
</div>
_message.html.erb
<tr>
<% if chat.user == current_user %>
<th>
<p style="text-align: left;" class="m-0 arrow_box"><%= chat.message %></p>
</th>
<th></th>
<% else %>
<th></th>
<th>
<p style="text-align: right;" class="m-0 arrow_box2"><%= chat.message %></p>
</th>
<% end %>
</tr>
create.js
$('#messages').append('<%= j(render 'message', chat: @chat) %>')
$('#chat_message').val('')
route.rb
resources :notifications, only: [:update]
chatのルートは参照したものに載っているはずです。
これで通知機能としては動くはずです。
Discussion