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.

Rails DM機能 showアクションの解説

Last updated at Posted at 2022-06-03

開発環境

Mac
Ruby 2.6.5
Rails 6.1.3.2

rooms/show.html.erb
<% @entries.each do |e| %>
<h5><strong><a href="/users/<%= e.user.id %>"><%= e.user.name%>さん</a></strong></h5>
<% end %>

<hr>
<% if @messages.present? %>
<% @messages.each do |m| %>
<strong><%= m.content %></strong>
<small>by <strong><a href="/users/<%= m.user_id %>"><%= m.user.name %>さん</a></strong></small>
<hr>
<% end %>
<%else %>
<h3 class="text-center">メッセージはまだありません</h3>
<% end %>

<%= form_for @message do |f| %>
<%= f.text_field :content, :placeholder => "メッセージを入力して下さい" , :size => 70 %>
<%= f.hidden_field :room_id, :value => @room.id %>
<br>
<%= f.submit "投稿する" %>
<% end %>
rooms_controller.rb
class RoomsController < ApplicationController
  def show
    @room = Room.find(params[:id])・・1
    if Entry.where(user_id: @current_user.id, room_id: @room.id).present?・・2
      @messages = @room.messages・・3
      @message = Message.new・・4
      @entries = @room.entries・・5
    else
      redirect_back(fallback_location: root_path)・・6
    end
  end
end

コードの解説

1・・1つのチャットルームを表示させる必要があるので、findメソッドを使います。
2・・Entriesテーブルに、現在ログインしているユーザーのidとそれにひもづいたチャットルームのidをwhereメソッドで探し、そのレコードがあるか確認します。
(補足whereメソッド==テーブル内の条件に一致したレコードを配列の形で取得することができるメソッド。)
3・・もし現在ログインしているユーザーのidとそれにひもづいたチャットルームのidがあったら、メッセージと名前を表示させるため、@messagesに@room.messagesを代入します。
4・・また、新しくメッセージを作成する場合は、Message.newをすることでメッセージのインスタンスが生成され、Message.newを@messageに代入させます。
5・・そしてrooms/show.html.erbでユーザーの名前などの情報を表示させるために、@room.entriesを@entriesというインスタンス変数に入れ、Entriesテーブルのuser_idの情報を取得します。
6・・もしidがなかったら、前のページに戻るための記述である、redirect_backを使います。

参考記事

RailsでややこしいDM機能を1万字でくわしく解説してみた
RailsでDM(ダイレクトメッセージ)を送れるようにしよう

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?