From a4e461bccee482c40e69be9310ba12de5d7da59b Mon Sep 17 00:00:00 2001 From: HombreLaser Date: Fri, 24 Mar 2023 20:34:23 -0600 Subject: Fixes de addresses_controller --- app/controllers/api/addresses_controller.rb | 11 ++++++++--- app/controllers/services/create_address_service.rb | 3 +-- app/controllers/services/update_address_service.rb | 1 + app/models/user_account.rb | 2 +- 4 files changed, 11 insertions(+), 6 deletions(-) (limited to 'app') diff --git a/app/controllers/api/addresses_controller.rb b/app/controllers/api/addresses_controller.rb index 4eda02d..ebe129b 100644 --- a/app/controllers/api/addresses_controller.rb +++ b/app/controllers/api/addresses_controller.rb @@ -12,8 +12,13 @@ module Api def create @service = Services::CreateAddressService.new(current_user_account, service_params) - unless @service.call - render json: { error_messages: @service.address.errors.full_messages }, status: :unprocessable_entity + begin + unless @service.call + render json: { error_messages: @service.address.errors.full_messages }, status: :unprocessable_entity + return + end + rescue ActiveRecord::RecordNotUnique + render json: { error_message: 'Ya cuenta con esta dirección' }, status: :unprocessable_entity return end @@ -55,7 +60,7 @@ module Api end def service_params - params.require(:number, :street, :zip_code, :country, :city) + params.permit(:number, :street, :zip_code, :country, :city) end end end diff --git a/app/controllers/services/create_address_service.rb b/app/controllers/services/create_address_service.rb index 7b67af2..5ded4f7 100644 --- a/app/controllers/services/create_address_service.rb +++ b/app/controllers/services/create_address_service.rb @@ -7,8 +7,7 @@ module Services def call if already_existing_address.nil? - @address = @user_account.address.new(@params) - @address.save + @address = @user_account.addresses.create(@params) else add_address_to_user_addresses @address = already_existing_address diff --git a/app/controllers/services/update_address_service.rb b/app/controllers/services/update_address_service.rb index 9f1ce54..26a596e 100644 --- a/app/controllers/services/update_address_service.rb +++ b/app/controllers/services/update_address_service.rb @@ -19,6 +19,7 @@ module Services return :unprocessable_entity unless @address.update(@params) else add_address_to_user_addresses + @address.user_account_addresses.find_by(user_account_id: @user_account.id).destroy @address.destroy if @address.user_accounts.count.zero? @address = already_existing_address end diff --git a/app/models/user_account.rb b/app/models/user_account.rb index 0f94003..ea6f9a6 100644 --- a/app/models/user_account.rb +++ b/app/models/user_account.rb @@ -8,7 +8,7 @@ # session_key: string class UserAccount < ApplicationRecord has_secure_password validations: false - has_many :user_account_addresses + has_many :user_account_addresses, dependent: :destroy has_many :addresses, through: :user_account_addresses validates :email, presence: true -- cgit v1.2.3