LoginSignup
0
0

More than 1 year has passed since last update.

【Rails】お気に入り機能いいね機能

Last updated at Posted at 2023-03-27

お気に入り機能(いいね機能)を付ける

「いいね機能」のテーブル設定

カラム名 データ型 カラム名説明
id integer いいねごとのid
user_id integer いいねしたユーザーのid
book_id integer いいねされた本のid

app/models/favorite.rb
class Favorite < ApplicationRecord

  belongs_to :user
  belongs_to :book
  
end

app/models/book.rb
class Book < ApplicationRecord

  belongs_to :user
  has_one_attached :image
  has_many :favorites, dependent: :destroy #これを追加
  :


  def favorited_by?(user)                   #この3行も追加
    favorites.exists?(user_id: user.id)
  end

end

app/models/user.rb
class User < ApplicationRecord

.
.

has_many :favorites, dependent: :destroy #追加
app/controllers/favortes_controller.rb
class FavoritesController < ApplicationController

  def create
    book = Book.find(params[:book_id])
    favorite = current_user.favorites.new(book_id: book.id)
    favorite.save
    redirect_to book_path(book)
  end

  def destroy
    book = Book.find(params[:book_id])
    favorite = current_user.favorites.find_by(book_id: book.id)
    favorite.destroy
    redirect_to book_path(book)
  end

end

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