Skip to content

Commit b1280ff

Browse files
committed
feat: Add CRUD actions with validations for Hotel model
1 parent ef17098 commit b1280ff

File tree

2 files changed

+44
-16
lines changed

2 files changed

+44
-16
lines changed

app/controllers/api/v1/hotel_controller.rb

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -72,6 +72,31 @@ def destroy
7272
render json: { error: 'Internal server error', message: e.message }, status: :internal_server_error
7373
end
7474

75+
def create_with_validations
76+
@hotel = Hotel.new(hotel_params)
77+
if @hotel.save
78+
render json: @hotel, status: :created
79+
else
80+
render json: { errors: @hotel.errors.full_messages }, status: :unprocessable_entity
81+
end
82+
end
83+
84+
def update_with_validations
85+
if @hotel.update(hotel_params)
86+
render json: @hotel
87+
else
88+
render json: { errors: @hotel.errors.full_messages }, status: :unprocessable_entity
89+
end
90+
end
91+
92+
def destroy_with_callback
93+
if @hotel.destroy
94+
head :no_content
95+
else
96+
render json: { errors: @hotel.errors.full_messages }, status: :unprocessable_entity
97+
end
98+
end
99+
75100
private
76101

77102
def set_hotel

app/models/hotel.rb

Lines changed: 19 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,3 @@
1-
# frozen_string_literal: true
2-
3-
# app/models/hotel.rb
41
class Hotel < CouchbaseOrm::Base
52
attribute :title, :string
63
attribute :name, :string
@@ -31,7 +28,17 @@ class Hotel < CouchbaseOrm::Base
3128
attribute :created_at, :datetime, precision: 6
3229
attribute :updated_at, :datetime, precision: 6
3330

31+
validates :name, presence: true, uniqueness: true
32+
validates :address, presence: true
33+
validates :phone, presence: true
34+
validates :type, inclusion: { in: ['hotel', 'motel', 'resort'] }
35+
validates :url, format: { with: URI.regexp, message: 'must be a valid URL' }
36+
validates :description, length: { maximum: 500 }
37+
38+
before_create :set_alias
3439
before_save :set_timestamps
40+
after_create :send_welcome_email
41+
before_destroy :check_reviews
3542

3643
private
3744

@@ -40,19 +47,15 @@ def set_timestamps
4047
self.created_at = current_time if new_record?
4148
self.updated_at = current_time
4249
end
43-
end
4450

45-
# app/models/geo_coordinates.rb
46-
class GeoCoordinates < CouchbaseOrm::NestedDocument
47-
attribute :lat, :float
48-
attribute :lon, :float
49-
attribute :accuracy, :string
50-
end
51+
def send_welcome_email
52+
# Code to send welcome email after hotel creation
53+
end
5154

52-
# app/models/review.rb
53-
class Review < CouchbaseOrm::NestedDocument
54-
attribute :content, :string
55-
attribute :ratings, :hash
56-
attribute :author, :string
57-
attribute :date, :datetime
55+
def check_reviews
56+
if reviews.any?
57+
errors.add(:base, 'Cannot delete hotel with existing reviews')
58+
throw :abort
59+
end
60+
end
5861
end

0 commit comments

Comments
 (0)