【发布时间】:2020-11-03 06:41:20
【问题描述】:
我正在使用 gem 设计来创建用户配置文件
每个用户都可以创建评论。我需要在每条评论旁边添加用户名 <%= @comment.user.name %>
在 user.rb 中
has_many :comments, dependent: :destroy
在comment.rb中
belongs_to :users
在评论控制器中
before_action :find_comment ,only:[:show,:update,:edit,:destroy]
def new
@user =User.find(params[:id])
@comment = @user.comments.build
end
def create
@user =User.find(params[:id])
@comment = @user.comments.build(comment_params)
@comment.user = current_user
if @comment.save
redirect_to doctor_path(:id => @user.id)
end
end
private
def find_comment
@comment = Comment.find(params[:id])
end
def comment_params
params.require(:comment).permit(:text)
end
用户控制器
def show
@user = User.find(params[:id])
end
用户 show.html.erb
<% for item in @user.comments %>
<% if item.text.present? %>
<%= item.text %><br>
<%= @comment.user.name %>
<br><hr>
<% end %>
我收到了这个错误
undefined method `user' for nil:NilClass
【问题讨论】:
-
我不清楚你的问题是什么。你想用电子邮件做什么?
-
@jamesc 我想为评论添加用户名。例如,我正在写评论,我的名字是 nourza。我的名字会显示在评论后面
-
您需要在某处使用comment.user.name,但您没有提供足够的信息来给出明确的答案
-
@jamesc 你需要什么信息?
-
我得到了这个错误 undefined method `user' for nil:NilClass
标签: ruby-on-rails database authentication devise comments