Files
astuto/app/controllers/posts_controller.rb

75 lines
1.7 KiB
Ruby
Raw Normal View History

2019-09-02 14:32:57 +02:00
class PostsController < ApplicationController
2019-09-12 15:51:45 +02:00
before_action :authenticate_user!, only: [:create, :update]
2019-09-02 19:26:34 +02:00
2019-09-04 17:37:08 +02:00
def index
2019-09-02 19:26:34 +02:00
posts = Post
2019-09-12 15:51:45 +02:00
.select(:id, :title, :description, :post_status_id)
2019-09-03 12:58:44 +02:00
.where(filter_params)
.search_by_name_or_description(params[:search])
2019-09-04 21:12:07 +02:00
.page(params[:page])
2019-09-19 14:00:34 +02:00
.order(updated_at: :desc)
2019-09-02 19:26:34 +02:00
render json: posts
2019-09-02 19:26:34 +02:00
end
2019-09-02 14:32:57 +02:00
def create
post = Post.new(post_params)
if post.save
render json: post, status: :no_content
2019-09-02 14:32:57 +02:00
else
render json: {
error: I18n.t('errors.post.create', message: post.errors.full_messages)
}, status: :unprocessable_entity
2019-09-02 14:32:57 +02:00
end
end
2019-09-12 15:51:45 +02:00
def show
@post = Post.find(params[:id])
2019-09-19 14:00:34 +02:00
@post_statuses = PostStatus.select(:id, :name, :color).order(order: :asc)
2019-09-12 15:51:45 +02:00
respond_to do |format|
format.html
format.json { render json: @post }
end
end
def update
post = Post.find(params[:id])
2019-09-16 19:38:56 +02:00
if !current_user.power_user? && current_user.id != post.user_id
2019-09-12 15:51:45 +02:00
render json: I18n.t('errors.unauthorized'), status: :unauthorized
2019-09-12 18:03:19 +02:00
return
2019-09-12 15:51:45 +02:00
end
post.post_status_id = params[:post][:post_status_id]
if post.save
render json: post, status: :no_content
else
render json: {
error: I18n.t('errors.post.update', message: post.errors.full_messages)
}, status: :unprocessable_entity
end
end
2019-09-02 14:32:57 +02:00
private
2019-09-03 12:58:44 +02:00
def filter_params
2019-09-05 17:11:07 +02:00
defaults = { board_id: Board.first.id }
2019-09-04 17:37:08 +02:00
params
.permit(:board_id, :post_status_id, :page, :search)
2019-09-04 17:37:08 +02:00
.with_defaults(defaults)
.except(:page, :search)
2019-09-03 12:58:44 +02:00
end
2019-09-02 14:32:57 +02:00
def post_params
params
.require(:post)
.permit(:title, :description, :board_id)
.merge(user_id: current_user.id)
2019-09-02 14:32:57 +02:00
end
end