LoginSignup
0
0

More than 3 years have passed since last update.

Rails6 each を使った時にDBのレコードの内容が全て出力されてしまう

Posted at

目的

  • eachを用いた時に意図しない出力になってしまったので解決方法を記載する。

症状

  • 下記のコードを用いてDBのとあるテーブルのレコードの内容を出力したところレコードの全ての内容が最後に出力されてしまう。

    <%= @posts.each do |post| %>
      <%= post.content %><br>
      <%= post.link %><br>
    <% end %>
    

    ↓出力

    testでーす
    https://qiita.com/miriwo
    [#<Post id: 1, content: "testでーす", created_at: "2020-02-08 00:54:38", updated_at: "2020-02-08 00:54:38", link: "https://qiita.com/miriwo">]
    

原因

  • 単純なミス
  • @posts.each do |post|の部分を<%= %>で囲んでしまっていたため、処理部分が出力されてしまった。

正しいコード

  • 下記に正しいコードを記載する。

    <% @posts.each do |post| %>
      <%= post.content %><br>
      <%= post.link %><br>
    <% end %>
    

    ↓出力

    testでーす
    https://qiita.com/miriwo
    

教訓

  • <%= %>は結果を出力したい時のみ使用する。
  • <% %>は結果を出力したくない時に使用する。
0
0
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
0