【发布时间】: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 %>
【问题讨论】:
-
该错误告诉您
user或comment是nil。一旦所有值都存在,您拥有的代码应该可以很好地显示用户的电子邮件。您是否正确地将comment值传递给部分? -
我认为您只需要将您的
comment链接到当前用户,例如@comment.user = current_user或@comment.user_id = current_user.id。您的current_user已经有一个电子邮件,您不必再次分配它。最后@comments.user和current_user在数据库中是同一条记录。
标签: ruby-on-rails ruby-on-rails-5 erb