mirror of
https://github.com/astuto/astuto.git
synced 2025-12-15 11:17:49 +01:00
Add likes model, controller and tests
This commit is contained in:
3
app/assets/stylesheets/likes.scss
Normal file
3
app/assets/stylesheets/likes.scss
Normal 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/
|
||||
33
app/controllers/likes_controller.rb
Normal file
33
app/controllers/likes_controller.rb
Normal 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
|
||||
2
app/helpers/likes_helper.rb
Normal file
2
app/helpers/likes_helper.rb
Normal file
@@ -0,0 +1,2 @@
|
||||
module LikesHelper
|
||||
end
|
||||
6
app/models/like.rb
Normal file
6
app/models/like.rb
Normal file
@@ -0,0 +1,6 @@
|
||||
class Like < ApplicationRecord
|
||||
belongs_to :user
|
||||
belongs_to :post
|
||||
|
||||
validates :user_id, uniqueness: { scope: :post_id }
|
||||
end
|
||||
@@ -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 }
|
||||
|
||||
@@ -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]
|
||||
|
||||
Reference in New Issue
Block a user