forked from AdaGold/video-store-api
-
Notifications
You must be signed in to change notification settings - Fork 25
Expand file tree
/
Copy pathrentals_controller.rb
More file actions
62 lines (50 loc) · 1.67 KB
/
rentals_controller.rb
File metadata and controls
62 lines (50 loc) · 1.67 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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
class RentalsController < ApplicationController
def create
rental = Rental.new(rental_params)
movie = Movie.find_by(id: rental_params[:movie_id])
customer = Customer.find_by(id: rental_params[:customer_id])
if movie.nil?
render json: {errors: "Movie with id #{rental_params[:movie_id]} doesn't exist"}, status: :bad_request
return
end
if movie.available_inventory == 0
render json: { errors: "No available inventory for #{movie.title}." }, status: :bad_request
return
end
if rental.save
movie.decrement_available_inventory
movie.save
customer.increment_movies_checked_out_count
customer.save
render json: { id: rental.id, due_date: rental.due_date }, status: :ok
else
render json: { errors: rental.errors.messages }, status: :bad_request
end
end
def update
rental = Rental.find_by(rental_params)
if rental.nil?
render json: { errors: "This rental does not exist." }, status: :bad_request
return
end
movie = rental.movie
customer = rental.customer
if rental.updated_at != rental.created_at
render json: { errors: "#{movie.title} is already checked-in." }, status: :bad_request
else
if rental.save
movie.increment_available_inventory
movie.save
customer.decrement_movies_checked_out_count
customer.save
render json: { id: rental.id, "check-in date": rental.updated_at }, status: :ok
else
render json: { errors: rental.errors.messages }, status: :bad_request
end
end
end
private
def rental_params
return params.require(:rental).permit(:movie_id, :customer_id)
end
end