LoginSignup
0
1

More than 3 years have passed since last update.

Rails6 each文にてeachがメソッドとして扱われて困った話

Last updated at Posted at 2021-02-10

目的

  • each文を使用してカラム内容を順に出力したい時にeachがメソッドとして扱われてしまって困ったときの解決法をまとめる

結論

  • each文で繰り返し処理の対象の変数に格納されている値を配列状態で格納する。

エラーの内容とエラー時のコード

  • 当該ページは@posts.contentに格納されている内容をeach文で次々渡し、表示する処理がある。
  • 当該ページへアクセスしたところ下記のエラーが発生した。

    undefined method `each' for #<Post:0x00007fac1ebd28e8>
    
  • エラーに関係するルーティングファイルの内容を記載する。

    get "posts/index/:id" => "posts#index"
    
  • エラーに関係するpostsコントローラファイルの内容を記載する。

    def index
      @posts = Post.find_by(id: params[:id])
    end
    
  • エラーに関係するindexビューファイルの内容を記載する。

    <% @posts.each do |post| %>
      <%= post.content %>
      <%= link_to("詳細", "/posts/#{post.id}") %>
    <% end %>
    

解決方法

  • 修正を行なったコードのみ下記に記載する。

    def index
      @posts = Post.where(id: params[:id])
    end
    
  • find_byメソッドは一致した最初のものを一つだけ返す。

  • whereメソッドは一致した全てのものを返す。

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