2013-07-29 44 views
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 

回答

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 

下一次,多花一點時間研究你的問題,這是一個常見的任務和一個非常簡短的谷歌搜索本來可以省去你問的麻煩。

+0

感謝您的回答,但是在我這樣做之後,旁邊的用戶名仍然是空的。在我的演出文件中,我使用了comment.user方法。這樣對嗎? – user2596615

+0

您可能正在尋找<%= Comment.user.fullname%> – XanderStrike

+0

畢竟,它工作。我創建了一個將user_id添加到評論控制器的遷移。無論如何,感謝您的幫助 – user2596615