From 8a7df9013262afaafa6649c89672cb227490eaac Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Elvis=20Serr=C3=A3o?= Date: Tue, 28 Jan 2025 13:30:00 -0300 Subject: [PATCH] Set categories list only for non parents --- app/controllers/categories_controller.rb | 21 ++++++++++++++++----- app/models/category.rb | 1 + 2 files changed, 17 insertions(+), 5 deletions(-) diff --git a/app/controllers/categories_controller.rb b/app/controllers/categories_controller.rb index 03752869..3c03969e 100644 --- a/app/controllers/categories_controller.rb +++ b/app/controllers/categories_controller.rb @@ -2,6 +2,7 @@ class CategoriesController < ApplicationController layout :with_sidebar before_action :set_category, only: %i[edit update destroy] + before_action :set_categories, only: %i[update edit] before_action :set_transaction, only: :create def index @@ -10,7 +11,7 @@ class CategoriesController < ApplicationController def new @category = Current.family.categories.new color: Category::COLORS.sample - @categories = Current.family.categories.alphabetically.where(parent_id: nil).where.not(id: @category.id) + set_categories end def create @@ -27,19 +28,21 @@ class CategoriesController < ApplicationController format.turbo_stream { render turbo_stream: turbo_stream.action(:redirect, redirect_target_url) } end else - @categories = Current.family.categories.alphabetically.where(parent_id: nil).where.not(id: @category.id) + set_categories render :new, status: :unprocessable_entity end end def edit - @categories = Current.family.categories.alphabetically.where(parent_id: nil).where.not(id: @category.id) end def update - @category.update! category_params + if @category.update(category_params) - redirect_back_or_to categories_path, notice: t(".success") + redirect_back_or_to categories_path, notice: t(".success") + else + render :edit, status: :unprocessable_entity + end end def destroy @@ -59,6 +62,14 @@ class CategoriesController < ApplicationController @category = Current.family.categories.find(params[:id]) end + def set_categories + @categories = unless @category.parent? + Current.family.categories.alphabetically.roots.where.not(id: @category.id) + else + [] + end + end + def set_transaction if params[:transaction_id].present? @transaction = Current.family.transactions.find(params[:transaction_id]) diff --git a/app/models/category.rb b/app/models/category.rb index 2a4e2799..d0ccaa60 100644 --- a/app/models/category.rb +++ b/app/models/category.rb @@ -15,6 +15,7 @@ class Category < ApplicationRecord validate :nested_category_matches_parent_classification scope :alphabetically, -> { order(:name) } + scope :roots, -> { where(parent_id: nil) } scope :incomes, -> { where(classification: "income") } scope :expenses, -> { where(classification: "expense") }