Only allow signed_in user to comment in the post
<p>Currently, I am using devise gem, I want only a signed_in user to comments in the post and display the flash message like "you must log_in to comment for the post" for the not sign_in user if they comment in the post. </p>

<p>This is my comments_controller.rb file</p>

<pre><code>  class CommentsController &lt; ApplicationController
  before_action :correct_user, only: :destroy

  def create
      @post = Post.find(params[:post_id])
      @comment = @post.comments.create(params[:comment].permit(:name, :body))
      @comment.user_id = current_user.id
      @comment.save


      redirect_to post_path(@post)      
  end

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

      redirect_to post_path(@post)
  end

  private

  def comment_params
    params.require(:comment).permit(:name, :body)
  end

  def correct_user
    @comment = current_user.comments.find_by(id: params[:id])
    if @comment.nil?
      flash[:alert] = "Not your comment!"
      redirect_to :back
    end
  end

end
</code></pre>

<p>Below is my _comment.html.erb file under views/comments folder</p>

<pre><code>&lt;div class="comment clearfix"&gt;
&lt;div class="comment_content"&gt;
    &lt;p class="comment_name"&gt;&lt;strong&gt;&lt;%= comment.name %&gt;&lt;/strong&gt;&lt;/p&gt;
    &lt;p class="comment_body"&gt;&lt;%= comment.body %&gt;&lt;/p&gt;
    &lt;p class="comment_time"&gt;&lt;%= time_ago_in_words(comment.created_at) %&gt; Ago&lt;/p&gt;
&lt;/div&gt;

&lt;% if user_signed_in? %&gt;
    &lt;p&gt;&lt;%= link_to 'Delete', [comment.post, comment],
                                  method: :delete,
                                  class: "button",
                                    data: { confirm: 'Are you sure?' } %&gt;
    &lt;/p&gt;
&lt;% end -%&gt;
</code></pre>

<p></p>

<p>and my comment model </p>

<pre><code>  class Comment &lt; ApplicationRecord
   belongs_to :post
   belongs_to :user
  end
</code></pre>