11
22

More than 3 years have passed since last update.

[Rails]いいねした商品をマイページに一覧表示する

Last updated at Posted at 2020-03-21

ユーザー(user)のマイページ(show)にいいね(like)した商品一覧を表示させます。
モデルの指定はこちらに記載してます。

 ルーティング

routes.rb
  resources :users, only: [:index, :show] do
    collection do
      get :likes
    end
  end

userのshowアクションにネストさせます。

モデル

user.rb
  has_many :likes, dependent: :destroy
  has_many :like_items, through: :likes, source: :item

※今回のポイント
like_itemsでuserがどのitemにいいねしているか取得できます。

 ビュー

users/_side-bar.html.haml
.side-bar
  %section.side-bar__group
    %h2.side-bar__group__title
      マイページメニュー
    %li.side-bar__group__list
      = link_to "お知らせ", "#"
    %li.side-bar__group__list
      = link_to "いいねした商品", likes_users_path

リンク先likes_users_path指定

users/likes.html.haml
.container-show 
  = render "side-bar"
  .main
    %section.main__group
      %h2.main__group__title
        〇〇さんのマイページ
    %section.main__table
      %h2.main__table__header
        いいね!一覧
      %ul.main__table__list
        - current_user.like_items.each do |item|
          %li
            =link_to item_path(item), class: "main__table__list__item" do
              %figure 
                = image_tag asset_path(item.images[0].content), :size =>'48x64'
              .main__table__list__item__body
                .main__table__list__item__body__text
                = item.name
                %br
                = item.price %i.fas.fa-chevron-right

likeファイルを作成
- current_user.like_items.each do |item|で現在ログインしているuserがいいねしたitemを取得しています。

=link_to item_path(item)で各商品詳細ページに遷移できるようにしてます。

完成イメージ

Image from Gyazo

Image from Gyazo

ご指摘ありましたらぜひコメントよろしくおねがいします!!

11
22
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
11
22