summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--app/controllers/api/addresses_controller.rb11
-rw-r--r--app/controllers/services/create_address_service.rb3
-rw-r--r--app/controllers/services/update_address_service.rb1
-rw-r--r--app/models/user_account.rb2
4 files changed, 11 insertions, 6 deletions
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