###背景
sessionを使った値の受け渡しを実装してみたい。
###問題点
ユーザのログインようなものは、sessionに
入れて保持することには成功したましたが、
例えば、
1つの記事の下にその記事に関してのコメントが複数表示されている状況で、
個々のコメントに対して返事がしたい場合に、
1つのコメントの情報をsessionに入れることがうまくできません。
自分が考えたのは、
返事のフォームがあるerbファイルが表示されるまでに記事に紐付いたコメントを変数に格納しる状態まで持って行って。
返事のフォームのview内で、
個々のコメントに展開するようにし、その際は、idだけ表示するようにして、
そのidをseessionに入れるということをしましたが、
結果的に一番最後のコメントのidが保持される形になってしまったため、
ifで返事のフォームが送信されたら入れるという条件をつくってみたが、
やはり一番最後のコメントのidが保持される形になってしまった。
なので、
どのように個々のコメントidをsessionに格納するのか、
少しだけヒントがほしいです。
よろしくお願いします。
###ソースコード
コメントに対する返事の投稿フォームはshow.html.erbにレンダーする形で表示します。
show.html.erb <%= @user.first_kanji%> <%= link_to '基本情報編集' ,edit_user_path(@user) %> <%= render 'follow_form' if logged_in? %> <hr /> <% if @user.microposts.any? %> <%= render partial: 'microposts/micropost', collection: @microposts %> <% end %>
userController class UsersController < ApplicationController before_action :set_user, only: [:show , :edit , :update ] def show @user = User.find(params[:id]) @microposts = @user.microposts @comments = @user.comments.build @replay = Replay.new if current_user.follower_relationships.any? if @user.id == current_user.id @follower_relationships = current_user.follower_relationships.find_by( params[:followed_id] == current_user.id) else @follower_relationships = current_user.follower_relationships.find_by(params[:follow_id] == @user.id , params[:followed_id] == current_user.id) end end if current_user.following_relationships.any? if @user.id == current_user.id @following_relationships = current_user.following_relationships.find_by(params[:follow_id] == current_user.id ) else @following_relationships = current_user.following_relationships.find_by(params[:follow_id] == current_user.id , params[:followed_id] == @user.id ) end end end
_micropost.html.erb <div id="micropost<%=micropost.id %>"> <% @micropost = micropost %> <p><%= micropost.user.first_kanji %> <%= micropost.user.last_kanji %>さん<br /> <%= micropost.content %> <% if current_user.following?(@user) && @following_relationships.status == 1 || current_user.follower?(@user) && @follower_relationships.status == 1 %> <%= render partial:'shared/comment_form' , locals:{comments: @micropost.comments} %> <% end %> <div id="comments<%=micropost.id %>"> <%= render partial: 'comments/comment' ,collection: @micropost.comments %> </div> <%- if current_user == micropost.user %> <%= link_to "削除", micropost , method: :delete , data:{confirm: "削除してよろしいですか?"} %> <% end %> </div> <hr />
_comment.html.erb *コメントを表示する箇所 <hr /> <div id="comment<%=comment.id %>"> <% @comment = comment %> <p><%= link_to " #{comment.user.first_kanji}", user_path %>さんがしたコメント</p> <p><%= comment.content %></p> <%= render 'shared/replay_form' , collection: @comment%> </div>
コメントに対する返事を作成する場所 _replay_form.html.erb <%= form_for(@replay, url: replays_path(:comment_id => @comment.id)) do |f| %> <%= f.text_field :content %> <%= f.submit "返信する" %> <% if(f.submit) %> <%= "a" %> <% end %> <% end %>
お手数おかけしますが、
宜しくお願いします。
あなたの回答
tips
プレビュー