###実装したい機能
Ajaxを利用したコメントの登録および部分更新による表示
###問題点
http://qiita.com/Yama-to/items/377f8a92cf30a3ebf454
上記記事のコメント機能を模倣してみたり、
RailsGuideを調べてました。
しかし、
Ajaxを利用して、サーバー側では、新しいコメントは登録されているのですが、
肝心なview側で部分更新がされません。
###解決したい点
どのように記述すれば、
部分更新がview側でも反映されるのでしょうか??
お手数おかけしますが、
アドバイス宜しくお願いします。
###ソースコード
show.html.erb <%= @user.first_kanji%> <%= link_to '基本情報編集' ,edit_user_path(@user) %> <%= render 'follow_form' if logged_in? %> <% if @user.microposts.any? %> <%= render partial: 'microposts/micropost', locals:{microposts: @microposts} %> <% end %>
_micropost.html.erb <% microposts.each do |micropost| %> <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' %> <% end %> <div id="comments<%=micropost.id %>"> <%= render partial: 'comments/comment' ,locals:{comments: @micropost.comments} %> </div> <%- if current_user == micropost.user %> <%= link_to "削除", micropost , method: :delete , data:{confirm: "削除してよろしいですか?"} %> <% end %> </div> <% end %>
_comment.html.erb <% comments.each do |comment| %> <div id="comment<%=comment.id %>"> <p><%= comment.content %></p> </div> <% end %>
_comment_form.html.erb <%= form_for(@comments,remote: true) do |f| %> <%= f.text_field :content , id: "comment_field" %> <%= hidden_field_tag :micropost_id , @micropost.id %> <%= hidden_field_tag :user_id , current_user.id %> <%= f.submit '投稿' %> <% end %>
CommentController class CommentsController < ApplicationController before_action :logged_in_user def create @user = User.find(params[:user_id]) @micropost = Micropost.find(params[:micropost_id]) @comment = current_user.comments.build(comment_params) @comment.micropost = @micropost respond_to do |format| if @comment.save @succeed = true format.html{redirect_to @user , notice: "Create Comment"} format.js {} format.json { render json: 'comments/comment', status: :created, location: @micropost.comments } else flash[:danger] = 'missing' end end end private def comment_params params.require(:comment).permit(:content) end end
create.js.erb <% if @succeed %> $("#comment_field").val(''); $(" $("#comments<%=@micropost.id %>" %>).innerHTML("<%= escape_javascript(render partial: 'comments/comment' , locals:{comments: @micropost.comments} )%> ); <% else %> <% end %>
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2016/04/23 17:30
2016/04/23 17:32