用户评论显示号码而不是用户名



我一直在努力弄清楚这一点,现在只是不能让它正常工作。我正在使用设计,我试图显示一个用户的用户名,评论了一个名为"坑"的对象,这基本上与博客文章相同,但有一些更多的功能。最初我发现它没有在我的评论模型中保存用户id,但我修复了这个问题,现在它只是渲染上面的内容。所有的搜索都得到了一些帮助,但没有找到完整的解决方案。欢迎所有的帮助和批评。谢谢。

页面正在显示下面的内容而不是名称

"<User: 0x00000105929950>" 

我有一个名为_comment.html的部分。代码应该在

下面呈现的动词
<p>
  <strong>Comment:</strong>
  <%= comment.body %>
  <%= comment.user %>
</p>
  <p>
  <%= link_to 'Destroy Comment', [comment.pit, comment],
               method: :delete,
               data: { confirm: 'Are you sure?' } %>
</p>

Controller:

class CommentsController < ApplicationController

 def create
  @pit= Pit.find(params[:pit_id])
  @comment = @pit.comments.build(comments_params)
  @comment.user = current_user
  @comment.save
  redirect_to pit_path(@pit)
end
def destroy
    @pit = Pit.find(params[:pit_id])
    @comment = @pit.comments.find(params[:id])
    @comment.destroy
    redirect_to pit_path(@pit)
  end
def show
end
  private
def comments_params
    params.require(:comment).permit(:body, :user_id)
end

结束

坑控制器

def index
  @pit = Pit.all
  @user = User.find_by(params[:id])
  @pit = @user.pits
  @pits = Pit.order('created_at DESC')
end
def create
  @user = current_user
  @pit = current_user.pits.create(pit_params)
    if @pit.save
      redirect_to @pit
    else
      render 'new'
    end
end
def show
  @pit = Pit.find(params[:id])
end
def edit
end
def update
end

private
def pit_params
    params.require(:pit).permit(:topic, :summary, :image, :video_url, :author, :user_id)
end

结束

用户控制器
class UsersController < ApplicationController
  before_filter :authenticate_user!

  def index
    @users = User.all
    authorize User
  end

   def show
    @user = User.find(params[:id])
  end


  def update
    @user = User.find(params[:id])
    authorize @user
    if @user.update_attributes(secure_params)
      redirect_to users_path, :notice => "User updated."
    else
      redirect_to users_path, :alert => "Unable to update user."
    end
  end
  def destroy
    user = User.find(params[:id])
    authorize user
    user.destroy
    redirect_to users_path, :notice => "User deleted."
  end
  private
  def secure_params
    params.require(:user).permit(:role)
  end
end

用户模型
class User < ActiveRecord::Base
  has_many :pits
  has_many :comments
  enum role: [:user, :vip, :admin]
  after_initialize :set_default_role, :if => :new_record?
  def set_default_role
    self.role ||= :user
  end
  def name
    name = first_name + ' ' + last_name
  end

  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,


 :recoverable, :rememberable, :trackable, :validatable
end

坑模型

class Pit < ActiveRecord::Base
  has_many :comments
  belongs_to :user
end

评论模型

class Comment < ActiveRecord::Base
  belongs_to :pit
  belongs_to :user
end

你需要写

comment.user.name

代替

comment.user

最新更新