お世話になります。
今回ajaxでコメント機能を作成しています。
投稿機能は作れたのですが、削除機能が上手くいきません。
ネットにも情報は有るのですが、上手く自分の状況に落とし込めません。
\app\controllers\comments_controller.rbファイル
class CommentsController < ApplicationController # コメントを保存、投稿するためのアクションです。 def create # ログインユーザーに紐付けてインスタンス生成するためbuildメソッドを使用します。 @comment = current_user.comments.build(comment_params) @blog = @comment.blog # respond_toは、クライアントからの要求に応じてレスポンスのフォーマットを変更します。 respond_to do |format| if @comment.save format.html { redirect_to blog_path(@blog), notice: 'コメントを投稿しました。' } format.json { render :show, status: :created, location: @comment } # JS形式でレスポンスを返します。 format.js { render :index } else format.html { render :new } format.json { render json: @comment.errors, status: :unprocessable_entity } end end end def destroy @comment = Comment.find(params[:id]) @comment.destroy render :js => { comment: @comment } end private # ストロングパラメーター def comment_params params.require(:comment).permit(:blog_id, :content) end end
\app\views\comments_form.html.erbファイル
<%= form_for([blog, comment], remote: true) do |f| %> <%= f.hidden_field :blog_id %> <div class="field"> <%= f.text_field :content, placeholder: "内容", class: "form-control" %> </div> <div class="actions"> <%= f.submit %> </div>] <% end %>
\app\views\comments_index.html.erbファイル
<ul> <% comments.each do |comment| %> <% unless comment.id.nil? %> <li> <p class="left"><%= comment.user.name %>さんがコメントしました。</p> <p class="left"><%= comment.content %></p> <% if current_user.id == comment.user.id %> <p class="right"> <%= link_to '', edit_blog_comment_path(blog, comment), class: "fa fa-pencil-square-o fa-lg" %> <%= link_to '', blog_comment_path(blog, comment), class: "fa fa-trash-o fa-lg", method: :delete, remote: true, data: { confirm: '本当に削除していいですか?' } %> </p> <% end %> </li> <% end %> <% end %> </ul>
app\views\comments\index.js.erbファイル
$("#comments_area").html("<%= j(render 'comments/index', { comments: @comment.blog.comments, blog: @comment.blog }) %>") $(':text').val('')
恐らくdestroyのjsファイルを作成してそれを読み込ませて処理するという事なのでしょうが記述方法、記述場所などがわかりません。
できればどこにどのように記述する、という風な回答をいただければと思います。
宜しくお願い致します。
あなたの回答
tips
プレビュー