Ruby on rails 如何显示向帖子写评论的用户的姓名(Rails)
我正在Rails上创建一个博客,里面有帖子、用户身份验证、设计、评论。若用户将写评论后,我想显示他的名字上面他的评论。我该怎么做?请帮帮我 我的意见:Ruby on rails 如何显示向帖子写评论的用户的姓名(Rails),ruby-on-rails,devise,blogs,Ruby On Rails,Devise,Blogs,我正在Rails上创建一个博客,里面有帖子、用户身份验证、设计、评论。若用户将写评论后,我想显示他的名字上面他的评论。我该怎么做?请帮帮我 我的意见: class CommentsController < ApplicationController def create @post = Post.find(params[:post_id]) @comment = @post.comments.build(params[:comment]) @comment.save redirect_to
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
只需在comments_controller.rb中分配用户
下次再花多一点时间研究你的问题,这是一项常见的任务,一次非常简短的谷歌搜索就可以省去你提问的麻烦。谢谢你的回答,但在我回答之后,评论旁边的用户名仍然是空的。在我的显示文件中,我使用comment.user方法。是吗?你可能在寻找毕竟,它成功了。我创建了一个迁移,将用户id添加到comments controller。不管怎样,谢谢你的帮助
def create
@post = Post.find(params[:post_id])
@comment = @post.comments.build(params[:comment])
@comment.user = current_user
@comment.save
redirect_to @post
end