/
Infernocasis
/
X.com
Обзор
Документация
Войти
/
Infernocasis
/
X.com
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
CI/CD
Аналитика
Безопасность
main
app/controllers/api/v1/posts_controller.rb
104 строки
3 KB
Infernocasis
Initial commit
08 июн 2025, 20:43
08 июн 2025, 20:43
68371ab
Код
Авторство
О чём код?
module Api module V1 class PostsController < ApplicationController def index posts = Post.includes(:user, :likes, :retweets).order(created_at: :desc) render json: posts.map { |post| post_with_user_info(post) } end def user_posts user = User.find(params[:user_id]) posts = Post.includes(:user, :likes, :retweets) .where('posts.user_id = ? OR EXISTS (SELECT 1 FROM retweets WHERE retweets.post_id = posts.id AND retweets.user_id = ?)', user.id, user.id) .order(created_at: :desc) render json: posts.map { |post| post_with_user_info(post) } rescue ActiveRecord::RecordNotFound render json: { error: 'User not found' }, status: :not_found end def create post = current_user.posts.build(post_params) if post.save render json: post_with_user_info(post), status: :created else render json: { errors: post.errors.full_messages }, status: :unprocessable_entity end end def show post = Post.includes(:user, :likes, :retweets).find(params[:id]) render json: post_with_user_info(post) rescue ActiveRecord::RecordNotFound render json: { error: 'Post not found' }, status: :not_found end def like post = Post.find(params[:id]) like = post.likes.build(user: current_user) if like.save render json: post_with_user_info(post) else render json: { errors: like.errors.full_messages }, status: :unprocessable_entity end end def unlike post = Post.find(params[:id]) like = post.likes.find_by(user: current_user) if like&.destroy render json: post_with_user_info(post) else render json: { error: 'Like not found' }, status: :not_found end end def retweet post = Post.find(params[:id]) retweet = post.retweets.build(user: current_user) if retweet.save render json: post_with_user_info(post) else render json: { errors: retweet.errors.full_messages }, status: :unprocessable_entity end end def unretweet post = Post.find(params[:id]) retweet = post.retweets.find_by(user: current_user) if retweet&.destroy render json: post_with_user_info(post) else render json: { error: 'Retweet not found' }, status: :not_found end end private def post_params params.require(:post).permit(:content) end def post_with_user_info(post) json = post.as_json(include: :user) retweet = post.retweets.find_by(user_id: current_user.id) if retweet json.merge!( original_author: post.user.as_json, retweeted_by: current_user.as_json ) end json.merge!( is_liked: post.likes.exists?(user: current_user), is_retweeted: post.retweets.exists?(user: current_user) ) end end end end