0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

記事に「いいね」機能②

Last updated at Posted at 2023-03-19

「いいね」機能

①config/routes.rb

    resource :like, only: [:create]

②app/views/articles/show.html.haml

  - if user_signed_in?
    .article_heart
      = link_to article_like_path(@article), data: { method: 'post' } do

③app/controllers/likes_controller.rb
作成

class LikesController < ApplicationController
  before_action :authenticate_user!

  def create
    article = Article.find(params[:article_id])
    article.likes.create!(user_id: current_user.id)
    redirect_to article_path(article)
  end
end

④いいねを実際にしようしてみて
保存できているかコンソールにて確認

$User.first.likes

とやると何かとれるのがわかります👍

$Article.find(1).likes

とやると保存できているのが確認できます👍

⑤いいねを押したらハートを赤にする機能
メソッドを定義する

app/models/user.rb

  def has_liked?(article)
    likes.exists?(article_id: article.id)
  end

likesの中にarticle idがあるかどうかで判断

⑥app/views/articles/show.html.haml

  .article_content
    = @article.content
  - if user_signed_in?
    -if current_user.has_liked?(@article)
        .article_heart
          = image_tag 'heart-active.svg'
    -else
        .article_heart
          = link_to article_like_path(@article), data: { method: 'post' } do
            = image_tag 'heart.svg'

これで、いいねを押すと赤くなるという機能が実装できました👍
※画像は事前に用意してあります!

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?