сохраните идентификатор сохраненного комментария в сеансе, а затем во время удаления или обновления проверьте сеанс на наличие идентификатора комментария и сравните текущее время с созданным комментарием в комментарии ... это можно использовать в методе фильтра.
Кроме того, вы можете переместить код поиска комментария с идентификатором в фильтре и следовать за DRY.
Вот так:
class CommentsController < ApplicationController
before_filter :get_blog
before_filter :get_comment, :only => [:edit, :update, :destroy]
before_filter :authorize_comment, :only => [:edit, :update, :destroy]
private
def get_blog
@blog = Blog.find(params[:blog_id])
end
def get_comment
@comment = Comment.find(params[:id])
end
def authorize_comment
unless @comment
flash[:error] = "Comment Not Found"
redirect_to @blog and return
else
# checks whether the comment is there in sessions' recent_comments
# if true, it means, this comment was created by the same visitor who is now attempting to delete/update it again
if session[:recent_comments].include?(@comment.id)
# now check if the comment is editable w.r.t time or not
if @comment.created_at < 10.minutes.ago
# if true, it means comment can no longer be updated/deleted
# if you wish you can now remove this from the session's recent_comments
session[:recent_comments].delete(@comment.id)
flash[:error] = "Sorry, you can not change this comment now"
redirect_to @blog and return
else
# it means comment can be edited/updated
return true
end
else
flash[:error] = "Sorry, you can not change this comment now"
redirect_to @blog and return
end
end
end
public
def new
@comment = Comment.new
respond_to do |format|
format.html # new.html.erb
format.xml { render :xml => @comment }
end
end
def edit
end
def create
params[:comment][:ip] = request.remote_ip
@comment = @blog.comments.create!(params[:comment])
unless session[:recent_comments].is_a?(Array)
session[:recent_comments] = []
end
session[:recent_comments] << @comment.id
redirect_to @blog
end
def update
respond_to do |format|
if @comment.update_attributes(params[:comment])
format.html { redirect_to(admin_comments_path, :notice => 'Comment was successfully updated.') }
format.xml { head :ok }
else
format.html { render :action => "edit" }
format.xml { render :xml => @comment.errors, :status => :unprocessable_entity }
end
end
end
def destroy
@comment.destroy
respond_to do |format|
format.html { redirect_to(admin_comments_url, :notice => 'Indlæg slettet') }
format.xml { head :ok }
end
end
end