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機能搭載 userコントローラー&ビュー

Last updated at Posted at 2021-05-12

忘れないための備忘録です。
railsのDM機能
(参考:https://qiita.com/nojinoji/items/2b3f8309a31cc6d88d03)

アソシエーションは
ルームとユーザーが エントリーとメッセージに対して1:多の関係

まずユーザーコントローラーのShow

def show
@user=User.find(params[:id]) #詳細ページのメイン(DMしたい相手)
@currentUserEntry=Entry.where(user_id: current_user.id) #ログインしている人が入っているルーム情報
@userEntry=Entry.where(user_id: @user.id) #詳細ページの人が入っているルーム情報
if @user.id == current_user.id #ログインしている人が自分のページを見ている
else
@currentUserEntry.each do |cu| #二人のルーム情報の中に
@userEntry.each do |u|
if cu.room_id == u.room_id then #二人のルームがあるなら
@isRoom = true  
@roomId = cu.room_id #この時にはcu,uともにお互いのルーム
end
end
end
if @isRoom #ないなら
else
@room = Room.new
@entry = Entry.new
end
end
end

user/show.html.erb のビュー

<%= @user.email %>

<% if @user.id == current_user.id %>  #自分が自分のマイページをみている

<% else %>
<% if @isRoom == true %>

チャットへ #二人のルームがあるなら二人のルームへのURLへ
<% else %>
<%= form_for @room do |f| %>  #@room = Room.new
<%= fields_for @entry do |e| %> #@entry = Entry.new
<%= e.hidden_field :user_id, :value=> @user.id %> #新たなentryのユーザーIDにshowのページの人(DMする相手)のIDを渡す役割
<% end %>
<%= f.submit "チャットを始める" %>
<% end %>
<% end %>
<% end %>

<%= link_to "ユーザー一覧に戻る", users_path %>

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?