LoginSignup
0
0

ブックマーク機能の実装

Posted at

ブックマーク機能を作る時はマイグレーションファイルを作ります。
以下のコードを使ってファイルを作成する。

rails generate migration CreateBookmarks

生成されたマイグレーションファイルを以下のような構成にします。

class CreateBookmarks < ActiveRecord::Migration[6.1]
  def change
    create_table :bookmarks do |t|
      t.references :user, null: false, foreign_key: true
      t.references :shop, null: false, foreign_key: true
      t.timestamps
    end
  end
end

次にブックマーク用のモデルを作成し、ユーザーモデルとショップモデルに関連付けます。


class Bookmark < ApplicationRecord
  belongs_to :user
  belongs_to :shop
end

class User < ApplicationRecord
  has_many :bookmarks
  has_many :shops, through: :bookmarks
end
class Shop < ApplicationRecord
  has_many :bookmarks
  has_many :users, through: :bookmarks
end

そして、次に対象となるpost的位置のコントローラーファイルにbookmarkアクションを作成する。

class ShopsController < ApplicationController
  def bookmark
    @shop = Shop.find(params[:id])
    current_user.bookmarks.create(shop: @shop)
    redirect_to @shop
  end
end

次に対象のモデルにルーティングを設定します。

resources :shops do
  member do
    post 'bookmark'
  end
end

次にviewファイルにブックマークボタンを追加します。

  <div class="bookmark_btn">
    <%= button_to 'ブックマークする', bookmark_shop_path(@shop), method: :post %>
  </div>

applicationコントローラーに current_user メソッドを定義します。これにより、現在ログインしているユーザーを取得できます。

  def current_user
    if session[:user_id]
      current_user ||= User.find(session[:user_id])
    end
  end

またブックマークボタンを星マークにする方法を記載します。
その場合はGem 'font-awesome-sass'をインストールする必要があります。
以下のコードをGemfileに書いた後、ターミナル上でbundle installを実行します。

gem 'font-awesome-sass'

app/assets/stylesheets/application.cssにimport文を加えます。

@import "font-awesome";

ブックマーボタンに関するコードを以下のものにすることで、ブックマーボタンを星マークに変えることができます。

<div class="bookmark_btn">
  <% if current_user.bookmarks.exists?(shop_id: @shop.id) %>
    <%= link_to bookmark_shop_path(@shop), method: :delete, class: "bookmark-btn" do %>
      <i class="fas fa-star bookmarked"></i>
    <% end %>
  <% else %>
    <%= button_to bookmark_shop_path(@shop), method: :post, class: "bookmark-btn" do %>
      <i class="far fa-star"></i>
    <% end %>
  <% end %>
</div>

次は星マークボタンのスタイルを構成するコードを書きます。

.bookmark-btn {
  background: none;
  border: none;
  cursor: pointer;
}

.bookmark-btn i {
  color: #ccc ;
}

.bookmark-btn i.bookmarked {
  color: gold;
}

これによりviewファイル上で星マークを表示させることができます。

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