0

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

我的评论控制器:

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
4

1 回答 1

-1

只需分配用户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

下次多花点时间研究你的问题,这是一项常见的任务,一个非常简短的谷歌搜索会省去你提问的麻烦。

于 2013-07-29T16:36:36.217 回答