参照
RailsでややこしいDM機能を1万字でくわしく解説してみた
疑問点
showアクションで定義されている@currentUserEntry
と@userEntry
にはwhereメソッドが使用されていますが、直下のunless
内でしか呼び出されていません。
であれば、unless
内で定義した方が、分岐の結果に関わらずクエリが毎回発行されてしまうのを防げるため良いのではないかと疑問に思いました。
現状では可読性を考慮して変数を最初にまとめて定義する書き方をされていると思うのですが、どちらの書き方の方が理想的なのでしょうか。
該当のソースコード
ruby:users_controller.rb
1class UsersController < ApplicationController 2 3 before_action :authenticate_user!, only: [:show] 4 5 def show 6 @user=User.find(params[:id]) 7 @currentUserEntry=Entry.where(user_id: current_user.id) 8 @userEntry=Entry.where(user_id: @user.id) 9 unless @user.id == current_user.id 10 @currentUserEntry.each do |cu| 11 @userEntry.each do |u| 12 if cu.room_id == u.room_id then 13 @isRoom = true 14 @roomId = cu.room_id 15 end 16 end 17 end 18 if @isRoom 19 else 20 @room = Room.new 21 @entry = Entry.new 22 end 23 end 24 end
erb:show.html.erb
1<% unless @user.id == current_user.id %> 2 <% if (current_user.followed_by? @user) && (@user.followed_by? current_user) %> 3 <% if @isRoom == true %> 4 <p class="user-show-room"><a href="/rooms/<%= @roomId %>" class="btn btn-primary btn-lg">チャットへ</a> 5 <% else %> 6 <%= form_for @room do |f| %> 7 <%= fields_for @entry do |e| %> 8 <%= e.hidden_field :user_id, value: @user.id %> 9 <% end %> 10 <%= f.submit "チャットを始める", class:"btn btn-primary btn-lg user-show-chat"%> 11 <% end %> 12 <% end %> 13 <% end %> 14<% end %>
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2022/07/29 09:03
2022/07/29 11:10