Files
astuto/app/controllers/likes_controller.rb

68 lines
1.5 KiB
Ruby
Raw Permalink Normal View History

2019-09-27 12:32:30 +02:00
class LikesController < ApplicationController
2019-09-30 16:54:37 +02:00
before_action :authenticate_user!, only: [:create, :destroy]
2024-05-03 18:11:07 +02:00
before_action :check_tenant_subscription, only: [:create, :destroy]
2019-09-30 16:54:37 +02:00
def index
likes = Like
.select(
:id,
:full_name,
:email,
'users.id as user_id', # required for avatar_url
2019-09-30 16:54:37 +02:00
)
.left_outer_joins(:user)
.where(post_id: params[:post_id])
.includes(user: { avatar_attachment: :blob }) # Preload avatars
likes = likes.map do |like|
2025-01-23 12:47:35 +01:00
user_avatar_url = like.user.avatar.attached? ? like.user.avatar.blob.url : nil
like.attributes.merge(user_avatar: user_avatar_url)
end
2019-09-30 16:54:37 +02:00
render json: likes
2019-09-30 16:54:37 +02:00
end
2019-09-27 12:32:30 +02:00
def create
like = Like.new(like_params)
if like.save
2019-09-30 16:54:37 +02:00
render json: {
id: like.id,
full_name: current_user.full_name,
email: current_user.email,
2025-01-23 12:47:35 +01:00
user_avatar: current_user.avatar.attached? ? current_user.avatar.blob.url : nil,
2019-09-30 16:54:37 +02:00
}, status: :created
2019-09-27 12:32:30 +02:00
else
render json: {
error: like.errors.full_messages
2019-09-27 12:32:30 +02:00
}, status: :unprocessable_entity
end
end
def destroy
2019-09-27 16:57:23 +02:00
like = Like.find_by(like_params)
2019-09-30 16:54:37 +02:00
id = like.id
2019-09-27 16:57:23 +02:00
return if like.nil?
2019-09-27 12:32:30 +02:00
if like.destroy
2019-09-30 16:54:37 +02:00
render json: {
id: id,
}, status: :accepted
2019-09-27 12:32:30 +02:00
else
render json: {
error: like.errors.full_messages
2019-09-27 12:32:30 +02:00
}, status: :unprocessable_entity
end
end
private
def like_params
2019-09-27 16:57:23 +02:00
{
post_id: params[:post_id],
user_id: current_user.id,
}
2019-09-27 12:32:30 +02:00
end
end