wblog/app/controllers/comments_controller.rb

48 lines
1.2 KiB
Ruby
Raw Normal View History

2014-03-30 22:14:59 +08:00
class CommentsController < ApplicationController
layout false
2016-04-29 23:37:52 +08:00
2014-03-30 22:14:59 +08:00
def index
@post = Post.find( params[:blog_id] )
res = @post.comments.desc(:created_at).collect { |comment| build_json(comment) }
render :json => res
end
def create
2016-04-29 23:37:52 +08:00
unless request.xhr?
2016-08-12 14:18:28 +08:00
logger.warn "attack action detected: #{params.to_h}"
2016-04-29 23:37:52 +08:00
redirect_to root_path
2016-08-12 14:18:28 +08:00
return
2016-04-29 23:37:52 +08:00
end
2016-04-23 14:47:50 +08:00
cookies[:name] = comment_params[:name]
cookies[:email] = comment_params[:email]
2014-03-30 22:14:59 +08:00
@post = Post.find( params[:blog_id] )
2016-04-23 14:47:50 +08:00
@comment = @post.comments.build(comment_params)
2014-06-03 23:25:45 +08:00
2016-04-23 14:47:50 +08:00
if @comment.save
@comments = @post.comments.order(created_at: :desc)
2016-04-28 11:18:53 +08:00
ActionCable.server.broadcast "comment_post_#{@comment.post.id}", { not: cookies[:cable_id] }
2016-04-23 14:47:50 +08:00
render :create_ok
2014-03-30 22:14:59 +08:00
else
2016-04-23 14:47:50 +08:00
render :create_fail
2014-03-30 22:14:59 +08:00
end
end
2016-04-28 11:18:53 +08:00
def refresh
@post = Post.find(params[:blog_id])
@comments = @post.comments.order(created_at: :desc)
end
2014-03-30 22:14:59 +08:00
private
def comment_params
2016-04-23 14:47:50 +08:00
params.require(:comment).permit(:content, :name, :email)
2014-03-30 22:14:59 +08:00
end
def build_json(comment)
{
content: comment.content,
name: comment.name,
'created_at' => format_time(comment.created_at)
}
end
end