gem devise如何添加创建用户电子邮件的评论? [英] gem devise how to add comment created user email?

查看:67
本文介绍了gem devise如何添加创建用户电子邮件的评论?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用gem devise创建用户个人资料 每个用户都可以创建一个评论.我需要在每个注释旁边添加用户名,例如<%= @comment.user.name %>

I am using gem devise for creating users profile Each user can create a comment. I need to add the user name beside each comment something like this <%= @comment.user.name %>

在user.rb

  has_many :comments, dependent: :destroy 

在comment.rb

in 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

user 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

推荐答案

您可以在show方法中以另一种方式进行操作:

You could do it the other way around, in your show method:

@comments = Comment.all

在您的show视图中:

<% @comments.each do |comment| %>
  <%= comment.text %>
  <%= comment.user.name %>
<% end %>

由于您的问题尚不清楚,我将明确指出,如果您只想显示用户发表的评论,则为:

Since your question is not really clear I'll specifiy that if you want to show just the comments posted by the user:

def show
  user_id = User.find(params[:id]).id
  @comments = Comment.where(user_id: user_id)
end

这篇关于gem devise如何添加创建用户电子邮件的评论?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆