将用户附加到评论

时间:2013-01-17 00:38:05

标签: ruby-on-rails ruby-on-rails-3 commenting

我有一个多态的工作评论系统,以便可以将评论添加到用户帖子。但是,我无法弄清楚如何将登录用户(评论者)附加到评论。

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

1 个答案:

答案 0 :(得分:0)

是不是像在save之前添加它一样简单?

@comment.commenter = current_user

您也可以在视图中添加它:

f.hidden_field :commenter_id, value: current_user.id

我想我更喜欢在视图中设置它。