Are you sure you want to delete the question?

If your question is resolved, you may close it.

Leaving a resolved question undeleted may help others!

We hope you find it useful!

投稿した画像を一覧表示させる際にランダム順で取得したレコードの表示させたい

プログラミング初学者です。
下記の解決したいことの投稿したものをランダム表示させるためにどうすれば良いか、
検索してみた結果。
整理が付かなくなりました。
まずitems_controller.rbにコードを書いてランダム表示させようとしたのですが、
うまくいかずどこに指示を出せばランダムで表示できるのか理解したいです。

解決したいこと

投稿した画像(アイテム)を一覧表示させる際に、
投稿した順ではなく、ランダム順で取得したレコードを表示させたいので、
解決方法を教えて下さい。

発生している問題・エラー

配列オブジェクト.sampleでランダム表示が出来るとwebに書いてあったが実行しても、
エラーが起こる。

class ItemsController < ApplicationController
  before_action :set_item, only: [:edit, :show]
  before_action :move_to_index, except: [:index, :show]

  def index
    @items = Item.includes(:user).sample
  end

  def new
    @item = Item.new
  end

  def create
    Item.create(item_params)
  end

  def destroy
    item = Item.find(params[:id])
    item.destroy
  end

  def edit
  end

  def update
    item = Item.find(params[:id])
    item.update(item_params)
  end

  def show
  end

  def set_item
    @item = Item.find(params[:id])
  end

  private
  def item_params
    params.require(:item).permit(:image, :text).merge(user_id: current_user.id)
  end

  def move_to_index
    unless user_signed_in?
      redirect_to action: :index
    end
  end
end

または、問題・エラーが起きている画像をここにドラッグアンドドロップ。
https://gyazo.com/ea7e0b247f4323e0d343a43ce073b6c3

NoMethodError in Items#index
Showing /Users/uraokayuutarou/projects/NF/app/views/items/index.html.erb where line #2 raised:

undefined method `each' for #<Item:0x00007fbe593c6e40>
Extracted source (around line #2):


<div class="contents row">
  <% @items.each do |item| %>
    <div class="content_post" style="background-image: url(<%= item.image %>);">
          <div class="more">
        <span><%= image_tag 'arrow_top.png' %></span>
        <ul class="more_list">

自分で調べてみた記事

qiita
【Rails】データベースからランダムにいくつかのレコードを取得する方法【ActiveRecord】
https://qiita.com/yutaroadachi/items/c48125e1c3f9b2403c38

テックアカデミー
sampleメソッド、suffleメソッドを使う
配列オブジェクト.sample
https://techacademy.jp/magazine/30661

teratail
Laravel ランダム順で取得したレコードを1ページずつで表示したいが、正しく取得できない
https://teratail.com/questions/196451
(PHPはまだ未学習なので、Ruby and railsで解決したい)

0

1Answer

Your answer might help someone💌