如何显示撰写评论的用户姓名(Rails)

时间:2013-07-29 15:55:49

标签: ruby-on-rails devise blogs

我正在使用帖子,用户(使用Devise进行身份验证),评论在Rails上创建博客。如果用户会在帖子上写评论我想在他的评论上面显示他的名字。我怎样才能做到这一点?拜托,帮帮我

我的评论控制器:

class CommentsController < ApplicationController
def create
@post = Post.find(params[:post_id])
@comment = @post.comments.build(params[:comment])
@comment.save
redirect_to @post
end

def destroy
@comment = Comment.find(params[:id])
@comment.destroy
redirect_to @comment.post
  end
end

我的模特:

class Comment < ActiveRecord::Base
attr_accessible :post_id, :text
belongs_to :post
belongs_to :user
end

class User < ActiveRecord::Base
has_many :posts, :dependent => :destroy
has_many :comments, :dependent => :destroy

validates :fullname,      :presence => true, :uniqueness => true
validates :password,      :presence => true
validates :email,         :presence => true, :uniqueness => true


devise :database_authenticatable, :registerable,
     :recoverable, :rememberable, :trackable, :validatable

attr_accessible :email, :password, :password_confirmation, :fullname
end


class Post < ActiveRecord::Base
attr_accessible :text, :title, :tag_list
acts_as_taggable

validates :user_id, :presence => true
validates :title,   :presence => true
validates :text, :presence => true

belongs_to :user
has_many :comments
end

1 个答案:

答案 0 :(得分:0)

只需在comments_controller.rb

中分配用户即可
def create
  @post = Post.find(params[:post_id])
  @comment = @post.comments.build(params[:comment])
  @comment.user = current_user
  @comment.save
  redirect_to @post
end

下次花一点时间研究你的问题,这是一个常见的任务,一个非常简短的谷歌搜索可以省去你的问题。