Add likes model, controller and tests

This commit is contained in:
riggraz
2019-09-27 12:32:30 +02:00
parent e1d8dbc281
commit 970cd6934c
13 changed files with 118 additions and 2 deletions

View File

@@ -0,0 +1,3 @@
// Place all the styles related to the likes controller here.
// They will automatically be included in application.css.
// You can use Sass (SCSS) here: http://sass-lang.com/

View File

@@ -0,0 +1,33 @@
class LikesController < ApplicationController
before_action :authenticate_user!
def create
like = Like.new(like_params)
if like.save
render json: like, status: :created
else
render json: {
error: I18n.t('errors.likes.create', message: like.errors.full_messages)
}, status: :unprocessable_entity
end
end
def destroy
like = Like.where(like_params)
if like.destroy
render json: {}, status: :no_content
else
render json: {
error: I18n.t('errors.likes.destroy', message: like.errors.full_messages)
}, status: :unprocessable_entity
end
end
private
def like_params
params.permit(:post_id).merge(user_id: current_user.id)
end
end

View File

@@ -0,0 +1,2 @@
module LikesHelper
end

6
app/models/like.rb Normal file
View File

@@ -0,0 +1,6 @@
class Like < ApplicationRecord
belongs_to :user
belongs_to :post
validates :user_id, uniqueness: { scope: :post_id }
end

View File

@@ -2,6 +2,7 @@ class Post < ApplicationRecord
belongs_to :board
belongs_to :user
belongs_to :post_status, optional: true
has_many :likes, dependent: :destroy
has_many :comments, dependent: :destroy
validates :title, presence: true, length: { in: 4..64 }

View File

@@ -4,6 +4,7 @@ class User < ApplicationRecord
:confirmable
has_many :posts, dependent: :destroy
has_many :likes, dependent: :destroy
has_many :comments, dependent: :destroy
enum role: [:user, :moderator, :admin]