LoginSignup
3
1

More than 1 year has passed since last update.

複数枚投稿した画像の1枚だけを表示する

Posted at

はじめに

スクリーンショット 2021-07-21 20.22.40(2).png

複数枚投稿の機能を実装し、投稿一覧ページは画像を一枚だけにしたいと思いました。
どのようにしたかアウトプットしていきます。

現在の記述内容

model.rb
class Model < ApplicationRecord

 #複数枚を記述
 has_many_attached :images

 with_options presence: true do
 #バリデーション内容省略
 validates :images #画像がないと投稿でいない
 end
end
model_controller.rb
class ModelController < ApplicationController

  def index
    @model = Model.includes(:user).order("created_at DESC").page(params[:page]).per(5)
  end

  def new
    @model = Model.new
  end

  def create
    @model = Model.new(model_params)
    if @model.save
      redirect_to root_path
     else
      render :new
    end
  end
  private
  def model_params
                          #複数枚画像は配列に入るため下記のように記述
    params.require(:model).permit(images: []).merge(user_id: current_user.id)
  end
end

どのように表示するか

複数枚投稿は配列の中に画像が入ります。

<%= image_tag model.images[0], class: "review-img"%>

配列の最初は必ず0なのでmodel.images[0]になります。

3
1
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
3
1