2013-01-17 77 views
0

我有一個工作評論系統是多態的,所以可以將評論添加到用戶帖子。但是,我無法弄清楚如何將註冊用戶(評論者)附加到評論。附加用戶評論

comments_controller.rb:

class CommentsController < ApplicationController 
before_filter :authenticate_user!, :only => [:create, :destroy] 

def index 
    @commentable = find_commentable 
    @comments = @commentable.comments 
end 

def new 
    @commentable = find_commentable 
end 

def create 
    @commentable = find_commentable 
    @comment = @commentable.comments.build(params[:comment]) 
    if @comment.save 
    flash[:notice] = "Successfully created comment." 
    redirect_to get_master 
    else 
    render :action => 'new' 
    end 
end 

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

    respond_to do |format| 
     format.html { redirect_to comments_url } 
     format.json { head :no_content } 
    end 
end 

protected 

def find_commentable 
    params.each do |name, value| 
    if name =~ /(.+)_id$/ 
     return $1.classify.constantize.find(value) 
    end 
    end 
    nil 
end 

def get_master 
    @parent = @comment.commentable 
    if @parent.respond_to?('commentable_type') 
     @comment = @parent 
     get_master 
    else 
     return @parent 
    end 
end 
end 

回答

0

是不是那麼簡單,save之前添加呢?

@comment.commenter = current_user 

您也可以將其添加在自己的看法:

f.hidden_field :commenter_id, value: current_user.id 

我想我寧願在視圖中設置它。

+0

這固定它,非常感謝! – anater