forked from AdaGold/video-store-api
-
Notifications
You must be signed in to change notification settings - Fork 26
Expand file tree
/
Copy pathrentals_controller.rb
More file actions
44 lines (38 loc) · 1.35 KB
/
rentals_controller.rb
File metadata and controls
44 lines (38 loc) · 1.35 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# frozen_string_literal: true
class RentalsController < ApplicationController
def checkout
rental = Rental.new(rental_params)
rental.save
if rental.movie && rental.customer
rental.movie.available_inventory -= 1
rental.movie.save
rental.customer.movies_checked_out_count += 1
rental.customer.save
rental.due_date = rental.created_at + 7
end
if rental.save
render json: rental.as_json(only: %i[customer_id movie_id]), status: :ok
else
render json: { errors: rental.errors.messages },
status: :bad_request
end
end
def checkin
customer = Customer.find_by(id: rental_params[:customer_id])
movie = Movie.find_by(id: rental_params[:movie_id])
rental = Rental.find_by(customer_id: rental_params[:customer_id], movie_id: rental_params[:movie_id])
if customer && movie && rental
rental.destroy
movie.update(available_inventory: movie.available_inventory + 1)
customer.update(movies_checked_out_count: customer.movies_checked_out_count - 1)
render json: { status: :ok }
else
render json: { errors: { rental: ["Rental not found for customer ID #{rental_params[:customer_id]}, and movie ID #{rental_params[:movie_id]}"] } },
status: :not_found
end
end
private
def rental_params
params.permit(:customer_id, :movie_id)
end
end