【问题标题】:How do I extract the user's email from a comment on a post in a rails forum app?如何从 Rails 论坛应用程序中的帖子评论中提取用户的电子邮件?
【发布时间】:2026-02-16 15:55:01
【问题描述】:

我需要能够在我的 rails 应用程序中显示评论帖子的用户的电子邮件。

我已经确保我的所有关联都是正确的,并且在 create 方法中我记录了 current_user.email@comment.user.email 两者都返回了正确的值。但是,在 _comment 部分中,我不断收到用户为 nil 的错误。

模型:

class Comment < ApplicationRecord
  belongs_to :post
  belongs_to :user
  validates :comment_text, presence: true
end

class Post < ApplicationRecord
  belongs_to :user
  has_many :comments, dependent: :destroy
  validates :title, presence: true
  validates :content, presence: true
end

class User < ApplicationRecord
  has_secure_password
  has_many :posts, dependent: :destroy
  has_many :comments, dependent: :destroy
  validates :email, presence: true, uniqueness: true
end 

控制器:

class CommentsController < ApplicationController
before_action :find_post, only: [:show, :create, :edit, :update, :destroy]

def index
    @comments = Comment.all.order('created_at ASC')
end

def show
end

def new
    @comment = Comment.new
end

def create
    @comment = @post.comments.create(comment_params)
    @comment.user_id = current_user.id
    @comment.user.email = current_user.email
    puts current_user.email
    puts @comment.user.email


    if @comment.save
        flash[:success] = 'Your comment has been added to the post'
        redirect_to post_path(@post)
    else
        flash.now[:error] = 'Something went wrong. Your comment was not added to the post'
        render 'new'
    end
end

def update
end

def edit
end

def destroy
end

private

def comment_params
    params.require(:comment).permit(:comment_text, :post)
end

def find_post
    @post = Post.find(params[:post_id])
end
end 

局部视图:

<p><%= comment.comment_text %></p>
<p><%= comment.user %></p>
<p><%= comment.user_id %></p>
<p><%= comment.user.email %>

帖子展示视图:

<div class="comment-div">
    <%= render @post.comments %>
</div>

我希望看到评论者的电子邮件,但我不断收到此错误:

undefined method `email' for nil:NilClass
Extracted source (around line #4):
2
3
4

<p><%= comment.user %></p>
<p><%= comment.user_id %></p>
<p><%= comment.user.email %>

【问题讨论】:

  • 该错误告诉您usercommentnil。一旦所有值都存在,您拥有的代码应该可以很好地显示用户的电子邮件。您是否正确地将 comment 值传递给部分?
  • 我认为您只需要将您的comment 链接到当前用户,例如@comment.user = current_user@comment.user_id = current_user.id。您的current_user 已经有一个电子邮件,您不必再次分配它。最后@comments.usercurrent_user在数据库中是同一条记录。

标签: ruby-on-rails ruby-on-rails-5 erb


【解决方案1】:

从 Rails 5 开始,所有 belongs_to 关联都是强制性的,除非另有说明。由于您的评论模型有belongs_to :user 没有可选键:belongs_to :user, optional: true,因此评论的创建将失败并回滚,因为它会造成数据库不一致(您将拥有没有任何用户的评论)。

要解决此问题,您有几个选择:

  1. 与其直接创建 cmets,不如构建一个(尚未保存),然后分配 user_id:
   @comment = @post.comments.build(comment_params) # This won't save to the database yet so it won't have any inconsistencies 
   @comment.user_id = current_user.id
   @comment.user.email = current_user.email #This line is unnecessary, the email is already assigned through the user relation
   @comment.save
  1. 第二种选择是将 user_id 添加到 comment_params,以便在表单中添加一个隐藏字段,包括 user_id = current_user.id

  2. 在模型的belongs_to 关系中添加optional: true 选项,但我不建议这样做。

如果您的评论创建正在回滚,您可以通过运行@comment.errors 来检查错误

【讨论】:

  • 好的,我尝试了前两个选项,但错误仍然存​​在。我没有尝试第三个选项,因为你说你不会推荐它。还有其他想法吗?
  • @JoshNismo 你能进入 Rails 控制台并尝试获取记录吗? Comment.last,看看有没有相关的user_id。如果是这样,那么将变量传递给部分就存在问题。你能不能补充一下你是如何渲染局部的?
  • 这里是Comment.lastirb(main):002:0&gt; Comment.last Comment Load (0.5ms) SELECT "comments".* FROM "comments" ORDER BY "comments"."id" DESC LIMIT ? [["LIMIT", 1]] =&gt; #&lt;Comment id: 13, comment_text: "Yes", created_at: "2019-07-05 17:38:40", updated_at: "2019-07-05 17:38:40", post_id: 2, user_id: 1&gt; irb(main):003:0&gt;我在这里重新渲染部分:&lt;div class="comment-div"&gt; &lt;%= render @post.comments %&gt; &lt;/div&gt;
  • 如果您注释掉显示电子邮件的第 (4) 行,第 (2) 行和 (3) 行会打印什么?您能否尝试更改 &lt;% @post.comments.each do |comment| %&gt;&lt;%= render partial: 'comment', locals: {comment: comment} %&gt; &lt;% end %&gt; 的渲染语法
  • 好的,所以我不得不稍微修改一下你的语法:&lt;% @post.comments.each do |comment| %&gt; &lt;%= render partial: 'comments/comment', locals: {comment: comment} %&gt; &lt;% end %&gt; 第 2 行和第 3 行得到的是:#&lt;User:0x000000000d4c8170&gt;1
最近更新 更多