image画像を一覧表示させる


画像の一覧表示の実装について実装

現在、プログラミングスクールにてフリマアプリを5名で実装中
少し手間取ったホーム画面の一覧表示の実装手順を載せます。
フロント実装は完了済みとします。

開発環境
rails 5.2.4.1
ruby 2.5.1

マークアップはhamlで行いました。

※アウトプットの為記述
※初学者向けに記述します

完成イメージ

※載せている写真は動物ですがあくまでテスト画像として載せているだけです。
 予めご了承ください。

まずはコントローラの記述から
今回は一覧の表示をしたいので対象のapp/controllers/home_controller.rbを編集

home_controller.rb

 class HomeController < ApplicationController
   def index
     @images = Image.all
     @items = Item.all
   end
 end

今回はフリマのitemテーブルとimageテーブルのデータを取得できるように一旦記述
これでアイテムテーブルとimegeテーブルのデータをホーム画面に持ってきます。
roteはすでにできている為、今回は追記はありませんでしたが、一応載せております

routes.rb

 Rails.application.routes.draw do
   devise_for :users
   root "home#index"
   resources :items, only: [:new, :create, :show, :edit, :destroy]
   resources :sendings, only: [:new, :create]
   resources :users, only: [:edit]
   resources :cards, only: [:new, :create, :index, :destroy]
   resources :orders, only: [:index, :new, :create] do  
     collection do
       get 'index', to: 'orders#index'
       post 'pay', to: 'orders#pay'
       get 'done', to: 'orders#done'
     end
   end
 end

次にhamlに追記


  .main__item__category
    %h2.main__item__category__title
      ピックアップカテゴリー
    .main__item__category__item_box
      = link_to "#", class: "main__item__category__item_box__title" do
        新規投稿商品
      %ul.main__item__brand__item_box__lists
        %li
       👉- @items.each do |item| 
       👉  = link_to item_path(id: item.id) ,class: 
"main__item__brand__item_box__lists--list, item_list" do
            - ft_image = item.images.first
            = image_tag ft_image.photo.url, class: 
"item_list__picture"
            .item_list__body
              %h3.item_list__body__name
                = item.name
              %ul
                %li.item_list__body__price 
                  = item.price 
                  = "円"
                %li.item_list__body__likes
                  = icon 'fas', 'star'
                  0
              %p (税込)     

今回はitemテーブルに紐づいているimageの最初のデータを取得したかった為、上記の👉のように追記いたしました。
この記述でデータを取得し表示まではできました。
あとはスクロールで画像がうまくスクロールするようにいたしました。
長くなりますのでスクロールは別の記事に載せたいと思います。