Add favorites controller and templates
Allows saving and deleting favorites
This commit is contained in:
parent
b2adbd0400
commit
b9140430e2
4 changed files with 53 additions and 0 deletions
42
app/controllers/api/v1/favorites_controller.rb
Normal file
42
app/controllers/api/v1/favorites_controller.rb
Normal file
|
|
@ -0,0 +1,42 @@
|
|||
class Api::V1::FavoritesController < Api::V1::ApiController
|
||||
before_action :set_party, only: ['create']
|
||||
|
||||
def create
|
||||
party_id = favorite_params[:party_id]
|
||||
party = Party.find(party_id)
|
||||
|
||||
if !current_user
|
||||
raise Api::V1::UnauthorizedError
|
||||
elsif party.user && current_user.id == party.user.id
|
||||
raise Api::V1::SameFavoriteUserError
|
||||
elsif Favorite.where(user_id: current_user.id, party_id: party_id).length > 0
|
||||
raise Api::V1::FavoriteAlreadyExistsError
|
||||
else
|
||||
ap "Create a new favorite"
|
||||
object = {
|
||||
user_id: current_user.id,
|
||||
party_id: favorite_params[:party_id]
|
||||
}
|
||||
|
||||
@favorite = Favorite.new(object)
|
||||
render :show, status: :created if @favorite.save!
|
||||
end
|
||||
end
|
||||
|
||||
def destroy
|
||||
raise Api::V1::UnauthorizedError unless current_user
|
||||
|
||||
@favorite = Favorite.where(user_id: current_user.id, party_id: favorite_params[:party_id]).first
|
||||
render :destroyed, status: :ok if @favorite && Favorite.destroy(@favorite.id)
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def set_party
|
||||
@party = Party.where("id = ?", params[:party_id]).first
|
||||
end
|
||||
|
||||
def favorite_params
|
||||
params.require(:favorite).permit(:id, :party_id)
|
||||
end
|
||||
end
|
||||
3
app/views/api/v1/favorites/base.json.rabl
Normal file
3
app/views/api/v1/favorites/base.json.rabl
Normal file
|
|
@ -0,0 +1,3 @@
|
|||
object :favorite
|
||||
|
||||
attributes :id, :user_id, :party_id, :created_at, :updated_at
|
||||
5
app/views/api/v1/favorites/destroyed.json.rabl
Normal file
5
app/views/api/v1/favorites/destroyed.json.rabl
Normal file
|
|
@ -0,0 +1,5 @@
|
|||
object false
|
||||
|
||||
node :destroyed do
|
||||
true
|
||||
end
|
||||
3
app/views/api/v1/favorites/show.json.rabl
Normal file
3
app/views/api/v1/favorites/show.json.rabl
Normal file
|
|
@ -0,0 +1,3 @@
|
|||
object @favorite
|
||||
|
||||
extends 'api/v1/favorites/base'
|
||||
Loading…
Reference in a new issue