0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

LINEみたいに自分のメッセージと自分以外のメッセージの表示場所を変えたい

Posted at

はじめに

 現在作成中のチャットアプリのメッセージ画面をLINEのように自分の送ったメッセージは右、自分以外のメッセージは左に表示させよと一日苦戦した。ググってもあまり記事が見つからなかったので、ここに記録しておく。

ポイントとして使ったもの

  • renderメソッド
  • if文
  • deviseのメソッド

コントローラー

messages_controller.rb
def index
    @class_room = ClassRoom.find(params[:class_room_id])
    @messages = @class_room.messages.includes(:user)
  end

@class_roomにチャットルームをparamsから呼び出し代入
@messagesにそのチャットルームのメッセージを全て入れる。
.includes(:user)はN+1問題を解消するため。

ビュー

※divタブはコードが読みにくくなるため、ここでは割愛。

<% if message.user.id == current_user.id %>
    <%= l message.created_at %>
    <%= message.content %>
<% else %>
    <%= message.user.last_name %>
    <%= l message.created_at %>
    <%= message.content %>
<% end %>

if文で、メッセージのユーザーIDと現在のログインしているユーザーが同じか照会し、同じであれば(つまり、自分の送ったメッセージ)上の処理が行われ、違えば、下の処理が行われる。
自分のメッセージに送り主の表示は必要ないので、上の処理にmessage.user.last_name がない。

その他

 CSSを整える。

終わりに

 他のやり方として、コントローラーの時点で、自分のメッセージと自分以外のメッセージを別の変数に入れる方法も考えられる。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?