2013-01-17 1 views
0

사용자가 사용자게시물에 추가 할 수 있도록 다형성이 작동하는 주석 시스템이 있습니다. 그러나 코멘트에 로그인 한 사용자 (코멘트 작성자)를 첨부하는 방법을 알아낼 수 없습니다.Comments에 사용자 연결

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

IT는 save 전에 추가로 간단하지 않습니다?

@comment.commenter = current_user 

또한보기에 추가 할 수 있습니다 :

f.hidden_field :commenter_id, value: current_user.id 

는 내가보기에 설정을 선호하는 거라고 생각합니다.

+0

이렇게 고쳐 주셔서 감사합니다. – anater