mirror of
https://github.com/astuto/astuto.git
synced 2025-12-15 19:27:52 +01:00
113 lines
2.9 KiB
Ruby
113 lines
2.9 KiB
Ruby
class PostsController < ApplicationController
|
|
before_action :authenticate_user!, only: [:create, :update]
|
|
|
|
def index
|
|
posts = Post
|
|
.select(
|
|
:id,
|
|
:title,
|
|
:description,
|
|
:post_status_id,
|
|
'COUNT(DISTINCT likes.id) AS likes_count',
|
|
'COUNT(DISTINCT comments.id) AS comments_count',
|
|
'((LOG(COUNT(DISTINCT likes.id) + 1) + LOG(COUNT(DISTINCT comments.id) + 1)) + (EXTRACT(EPOCH FROM posts.created_at) / 45000)) AS hotness',
|
|
"(SELECT COUNT(*) AS liked FROM likes WHERE likes.user_id=#{current_user ? current_user.id : -1} AND likes.post_id=posts.id)"
|
|
)
|
|
.left_outer_joins(:likes)
|
|
.left_outer_joins(:comments)
|
|
.group('posts.id')
|
|
.where(filter_params)
|
|
.search_by_name_or_description(params[:search])
|
|
.order('hotness DESC')
|
|
.page(params[:page])
|
|
|
|
render json: posts
|
|
end
|
|
|
|
def create
|
|
post = Post.new(post_params)
|
|
|
|
if post.save
|
|
Follow.create(post_id: post.id, user_id: current_user.id)
|
|
|
|
render json: post, status: :created
|
|
else
|
|
render json: {
|
|
error: post.errors.full_messages
|
|
}, status: :unprocessable_entity
|
|
end
|
|
end
|
|
|
|
def show
|
|
@post = Post.find(params[:id])
|
|
@post_statuses = PostStatus.select(:id, :name, :color).order(order: :asc)
|
|
@board = @post.board
|
|
|
|
respond_to do |format|
|
|
format.html
|
|
|
|
format.json { render json: @post }
|
|
end
|
|
end
|
|
|
|
def update
|
|
post = Post.find(params[:id])
|
|
|
|
if !current_user.power_user? && current_user.id != post.user_id
|
|
render json: t('backend.errors.unauthorized'), status: :unauthorized
|
|
return
|
|
end
|
|
|
|
post.board_id = params[:post][:board_id] if params[:post].has_key?(:board_id)
|
|
|
|
post_status_changed = false
|
|
|
|
if params[:post].has_key?(:post_status_id) and
|
|
params[:post][:post_status_id] != post.post_status_id
|
|
|
|
post_status_changed = true
|
|
post.post_status_id = params[:post][:post_status_id]
|
|
end
|
|
|
|
if post.save
|
|
if post_status_changed
|
|
PostStatusChange.create(
|
|
user_id: current_user.id,
|
|
post_id: post.id,
|
|
post_status_id: post.post_status_id
|
|
)
|
|
|
|
send_notifications(post)
|
|
end
|
|
|
|
render json: post, status: :no_content
|
|
else
|
|
render json: {
|
|
error: post.errors.full_messages
|
|
}, status: :unprocessable_entity
|
|
end
|
|
end
|
|
|
|
private
|
|
|
|
def filter_params
|
|
defaults = { board_id: Board.first.id }
|
|
|
|
params
|
|
.permit(:board_id, :post_status_id, :page, :search)
|
|
.with_defaults(defaults)
|
|
.except(:page, :search)
|
|
end
|
|
|
|
def post_params
|
|
params
|
|
.require(:post)
|
|
.permit(:title, :description, :board_id)
|
|
.merge(user_id: current_user.id)
|
|
end
|
|
|
|
def send_notifications(post)
|
|
UserMailer.notify_followers_of_post_status_change(post: post).deliver_later
|
|
end
|
|
end
|