如何保存current_user电子邮件并将其显示给用户?

时间:2016-11-18 13:15:21

标签: ruby-on-rails devise

我正在制作rails博客,我想制作评论作者可以匿名或current_user的功能,具体取决于是否登录。

如何保存current_user电子邮件并将其显示给用户?我想我没有正确连接用户和评论?

当我尝试保存评论时,我得到用户必须存在的错误。当我手动设置user_id时,@commenter为空。

这是评论控制器:

class CommentsController < ApplicationController

  def new
    @post = Post.find(params[:post_id])
    @comment = @post.comments.new(comment_params)
    @user = current_user if user_signed_in?
  end

  def create
    @post = Post.find(params[:post_id])
    @comment = @post.comments.build(comment_params)

    if user_signed_in?
      @user = current_user
      @user.id = current_user.id
      @user.comments.build(comment_params)
      @commenter = @user.email
    end

    if @comment.save
      flash[:success] = "Successfuly created comment!"
      redirect_to post_path(@post)
    else
      render :new
    end
  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(:text)
  end
end

我有部分内容,但不起作用,为什么?

<%= @commenter %>

至于模特:评论belongs_to用户和帖子。用户和帖子有很多评论。

这是发布评论部分的帖子的show.html.erb:

...
<%= render @post.comments %>
<%= render 'comments/form' %>

我做错了什么?

0 个答案:

没有答案