0
我在Rails上創建了一篇關於帖子,用戶(用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
感謝您的回答,但是在我這樣做之後,旁邊的用戶名仍然是空的。在我的演出文件中,我使用了comment.user方法。這樣對嗎? – user2596615
您可能正在尋找<%= Comment.user.fullname%> – XanderStrike
畢竟,它工作。我創建了一個將user_id添加到評論控制器的遷移。無論如何,感謝您的幫助 – user2596615