class Main::PostsController < ApplicationController before_action :authenticate_user!, except: %i[index show] before_action :ensure_frame_response, only: [:new, :edit] def index @communities = Main::Community.all # https://www.bearer.com/blog/infinite-scrolling-pagination-hotwire @pagy, @posts = pagy_countless( Main::Post.where("title LIKE ?", "%#{ params[:query] }%") .order(created_at: :desc), countless_minimal: true, items: 6 ) respond_to do |format| format.html # GET format.turbo_stream # POST end @post = Main::Post.new end def show @post = Main::Post.includes(comments: %i[comments author]).find(params[:id]) end def create @post = current_user.posts.build(post_params) if @post.save format.turbo_stream { render turbo_stream: turbo_stream.prepend("main_posts", partial: "main/posts/post", locals: { post: @post }) } format.html { redirect_to main_community_path(@post.main_community_id), notice: t("post_successfully_created") } else redirect_to main_communities_url, alert: t("something_went_wrong") end end def edit @post = current_user.posts.find(params[:id]) end def update @post = current_user.posts.find(params[:id]) if @post.update(post_params) format.turbo_stream { render turbo_stream: turbo_stream.replace(@post, partial: "main/posts/post", locals: { post: @post }) } format.html { redirect_to @post, notice: t("post_successfully_updated") } else render :edit end end def destroy @post = current_user.posts.find(params[:id]) @post.destroy! redirect_to @post.community, notice: t("post_successfully_destroyed") end private def post_params params.require(:post).permit(:title, :body, :community_id, images: []) end def ensure_frame_response return unless Rails.env.development? redirect_to root_path unless turbo_frame_request? end end