Created
September 17, 2010 23:56
-
-
Save kelper/585167 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class CommentsController < ApplicationController | |
before_filter :authenticate, :only => [:create, :edit, :update, :destroy] | |
before_filter :correct_user, :only => [:edit, :update, :destroy] | |
def new | |
@commentable = find_commentable | |
@comment = Comment.new | |
@comment.parent_id = params[:in_reply_to] if params[:in_reply_to] | |
end | |
def create | |
@commentable = find_commentable | |
if @commentable.nil? # Threaded Comments | |
@comment = Comment.new(params[:comment]) | |
else | |
@comment = @commentable.comments.build(params[:comment]) | |
end | |
@comment.user_id = current_user.id | |
if @comment.save | |
flash[:success] = "Comment saved." | |
redirect_to polymorphic_path(@commentable) | |
else | |
flash[:error] = "Error in creating comment." | |
# @comments = @commentable.comments.paginate(:page => params[:page]) | |
render 'new' | |
end | |
end | |
def destroy | |
@commentable = find_commentable | |
if @commentable.comments.find(params[:id]).destroy | |
flash[:success] = "Comment deleted." | |
else | |
flash[:error] = "Comment could not be deleted." | |
end | |
redirect_to @commentable | |
end | |
def edit | |
@commentable = find_commentable | |
@comment = @commentable.comments.find(params[:id]) | |
@title = "Edit Comment" | |
# The following code allows editing directly on the article page. | |
# @comments = @article.comments.paginate(:page => params[:page]) | |
# render 'articles/show' | |
end | |
def update | |
@commentable = find_commentable | |
@comment = @commentable.comments.find(params[:id]) | |
if @comment.update_attributes(params[:comment]) | |
flash[:success] = "Updated Comment" | |
redirect_to @commentable | |
else | |
flash[:error] = "Comment update failed." | |
@comments = @commentable.comments.paginate(:page => params[:page]) | |
render 'edit' | |
end | |
end | |
private | |
def find_commentable | |
params.each do |name, value| | |
if name =~ /(.+)_id$/ | |
return $1.classify.constantize.find(value) | |
end | |
end | |
nil | |
end | |
def authenticate | |
deny_access unless signed_in? | |
end | |
def correct_user | |
@commentable = find_commentable | |
redirect_to(@commentable) unless current_user.admin? | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment