前提・実現したいこと
Rails6.0.3でDM機能を実装中に以下のエラーメッセージが発生しました。
発生している問題・エラーメッセージ
ActionController::UrlGenerationError in RoomsController#create No route matches {:action=>"show", :controller=>"rooms", :id=>nil}, missing required keys: [:id] Parameters: {"authenticity_token"=>"KS15OrvWiRrpsJHSybYAgUF64SK6hn/9xK5DyAkwr1/dg5yxKgwMiJKtjriDv3oWHKN3zQd300y4l5n9Tkh9Gg==", "entry"=>{"user_id"=>"1"}, "commit"=>"チャットを始める"} Toggle session dump Toggle
該当のソースコード
users_controller.rb
class UsersController < ApplicationController def show @user = User.find(params[:id]) @microposts = @user.microposts @currentUserEntry=Entry.where(user_id: current_user.id) @userEntry=Entry.where(user_id: @user.id) unless @user.id == current_user.id @currentUserEntry.each do |cu| @userEntry.each do |u| if cu.room_id == u.room_id then @isRoom = true @roomId = cu.room_id end end end if @isRoom else @room = Room.new @entry = Entry.new end end end end
app/views/users/show.html/erb
<% unless @user.id == current_user.id %> <% if @isRoom == true %> <p class="user-show-room"><a href="/rooms/<%= @roomId %>" class="btn btn-primary btn-lg">チャットへ</a> <% else %> <%= form_for @room do |f| %> <%= fields_for @entry do |e| %> <%= e.hidden_field :user_id, value: @user.id %> <% end %> <%= f.submit "チャットを始める", class:"btn btn-primary btn-lg user-show-chat"%> <% end %> <% end %> <% end %>
rooms_controller.rb
class RoomsController < ApplicationController before_action :authenticate_user! def create @room = Room.create(:name => "DM") @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)) redirect_to room_path(@room.id) 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
routes.rb
Rails.application.routes.draw do devise_for :users, controllers:{ registrations: 'users/registrations', sessions: 'users/sessions' } resources :users , only: [:show] resources :microposts do resource :favorites, only: [:create, :destroy] end resources :messages, only: [:create] resources :rooms, only: [:create,:show] root 'public#home' get 'public/show' # For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html end
試したこと
rooms_controller.rbのcreateアクションに
binding.pryで@roomを調べたところ
<Room id: nil, created_at: nil, updated_at: nil, name: "DM">
Room_idがnilになっているのが原因の様です。
どう実装すればRoom_idが作成されデバッグできますか?
どうぞよろしくお願いします。
あなたの回答
tips
プレビュー