Overtaken by flash messages after adding Ajax



  • Flash messages have ceased to work after adding Ajax to create and delete the comment. What's the matter?

        class CommentsController < ApplicationController
    

    def create
    @post = Post.find(params[:post_id])
    @comment = @post.comments.create(comment_params)
    @comment.user_id = current_user.id
    if @comment.save
    respond_to do |format|
    format.html do
    flash[:success] = "Your comment has been posted."
    redirect_to @post
    end
    format.js
    end
    else
    flash.now[:danger] = "error"
    respond_to do |format|
    format.html { render @post }
    format.js
    end
    end
    end

    def destroy
    @post = Post.find(params[:post_id])
    @comment = Comment.find(params[:id])
    @comment.destroy

    respond_to do |format|
      format.html do
        flash[:success] = "Comment deleted."
        redirect_to post_path(@post)
      end
      format.js
    end
    

    end

    private
    def comment_params
    params.require(:comment).permit(:user_id, :content)
    end
    end

    create.js.erb:

    $('#comments-list').append('<%= escape_javascript(render @comment) %>');
    $("#commentCount").html("Comments(<%= @post.comments.count %>)");

    destroy.js.erb:

    $("#comments-list").html("<%= escape_javascript(render @post.comments) %>");
    $("#commentCount").html("Comments(<%= @post.comments.count %>)");

    All project code: https://bitbucket.org/Tiazar/callboard



  • Well, you don't give them any uniforms.

    1. You do. flash[:success] = "Comment deleted." Only if you're gonna rent html. I guess it's better to get out of this line. respond_to

    2. In you app/views/layouts/application.html.erb is the code:

    <% flash.each do |key, value| %>
      <div class="alert alert-<%= key %>">
        <%= value %>
      </div>
    <% end %>
    

    He's the one who displays these messages at the back page. In case you give an answer to the oyacs, this code doesn't play the rrendering. You need to take this piece of code, for example, app/views/layouts/_flash.html.erbThen, app/views/layouts/application.html.erb Instead, make:

    <div class="JS-headers">
      <%= render 'layouts/flash' %>
    </div>
    

    And in your js-presentation, add the line:

    $(".JS-headers").html("<%=j render 'layouts/flash' %>");
    



Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2