仅允许signed_in用户在帖子

时间:2016-08-28 17:08:25

标签: ruby-on-rails devise

目前,我正在使用devise gem,我只希望一个signed_in用户在帖子中发表评论并显示flash消息,例如"你必须log_in评论帖子"对于not sign_in用户,如果他们在帖子中发表评论。

这是我的comments_controller.rb文件

  class CommentsController < 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

以下是我在view / comments文件夹

下的_comment.html.erb文件
<div class="comment clearfix">
<div class="comment_content">
    <p class="comment_name"><strong><%= comment.name %></strong></p>
    <p class="comment_body"><%= comment.body %></p>
    <p class="comment_time"><%= time_ago_in_words(comment.created_at) %> Ago</p>
</div>

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

和我的评论模型

  class Comment < ApplicationRecord
   belongs_to :post
   belongs_to :user
  end

1 个答案:

答案 0 :(得分:0)

在您的新动作或创建动作中,您可以使用。您也可以将其作为before_action过滤器

    unless user_signed_in?
      flash[:notice] = "you must log_in to comment for the post"
      redirect_to #your login page
    end

花一些时间浏览文档http://github.com/plataformatec/devise