LoginSignup
0
0

More than 1 year has passed since last update.

rails でDM機能 rooms編

Posted at

rooms コントローラー
class RoomsController < ApplicationController
before_action :authenticate_user!

def create
@room = Room.create 

エントリー情報は一つのルームにつき二つ

@entry1 = Entry.create(:room_id => @room.id, :user_id => current_user.id)  #ログインしているユーザーのエントリー情報を登録
@entry2 = Entry.create(params.require(:entry).permit(:user_id, :room_id).merge(:room_id => @room.id)) #showで受け取った情報
redirect_to "/rooms/#{@room.id}" #roomのshowへ

end

def show
@room = Room.find(params[:id]) #二通りのもらい方 新しいのか前のか
if Entry.where(:user_id => current_user.id, :room_id => @room.id).present? #エントリー情報があるか
@messages = @room.messages #ルームが持つメッセージ
@message = Message.new 
@entries = @room.entries #ルームはエントリーを二つもっている。
else #なければ違う人のルームに入ろうとしているということ
redirect_back(fallback_location: root_path)
end
end
end

ルームのshowビュー

<% @entries.each do |e| %>

二つのエントリー情報をもとに、アソシエーションつたってIDとe-mailを取得

<% end %>



<% if @messages.present? %> #messagesはルームにあるすべてのメッセージ
<% @messages.each do |m| %>
<%= m.content %>
by
メッセージはまだありません
<% end %>

<%= form_for @message do |f| %> # @messageはカラのメッセージ
<%= f.text_field :content, :placeholder => "メッセージを入力して下さい" , :size => 70 %>
<%= f.hidden_field :room_id, :value => @room.id %>


<%= f.submit "投稿する" %>
<% 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