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
72 lines (60 loc) · 1.82 KB
/
rentals_controller.rb
File metadata and controls
72 lines (60 loc) · 1.82 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
63
64
65
66
67
68
69
70
71
72
class RentalsController < ApplicationController
RENTAL_LIMIT = 7 #days
def check_out
rental = Rental.new(rental_params)
rental.check_out = DateTime.now
rental.due_date = rental.check_out + RENTAL_LIMIT
movie = Movie.find_by(id: params[:movie_id])
unless movie
render json: {
errors: {
movie_id: ["No movie with ID #{params[:movie_id]}"]
}
}, status: :not_found
return
end
if movie.available_inventory < 1
render json: {
errors: {
available_inventory: ["#{movie.title} is not currently available."]
}
}, status: :not_found
return
end
duplicate_rental = Rental.find_rental(params[:movie_id], params[:customer_id])
if duplicate_rental
render json: {
errors: {
movie_id: ["#{movie.title} is currently checked out by that customer. A customer may not check out more than one copy of a movie at a time."]
}
}, status: :bad_request
return
end
if rental.save
render json: rental.as_json(only: [:movie_id, :customer_id]), status: :ok
else
render json: { errors: rental.errors.messages }, status: :bad_request
end
end
def check_in
rental = Rental.find_rental(params[:movie_id], params[:customer_id])
unless rental
render json: {
errors: {
rental: ["There is no outstanding rental with that criteria."]
}
}, status: :not_found
return
end
rental.update_attributes(check_in: DateTime.now)
if rental.save
render json: rental.as_json(only: [:movie_id, :customer_id]), status: :ok
else
render json: { errors: rental.errors.messages }, status: :bad_request
end
end
private
def rental_params
return params.permit(:movie_id, :customer_id)
end
end