【问题标题】:Attaching User to Comments将用户附加到评论
【发布时间】:2012-12-31 11:31:08
【问题描述】:

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

cmets_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

【问题讨论】:

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


    【解决方案1】:

    不就是在save前面加上那么简单吗?

    @comment.commenter = current_user
    

    您也可以将其添加到您的视图中:

    f.hidden_field :commenter_id, value: current_user.id
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-09-21
      • 2017-12-17
      • 2012-09-28
      • 2021-12-30
      • 1970-01-01
      • 2017-01-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多