LoginSignup
1
0

More than 3 years have passed since last update.

[Rails]views ファイル作成#textが表示される

Posted at

#textが表示される

表示していない#textという文字列が表示されたので、調査しました。

スクリーンショット 2020-12-30 23.17.14.png

間違ったソースコード index.html.erb↓

<h1>トップページ</h1>
<%= @posts.each do |post| %>
  <div>
    <%= post.memo %>
    <%= post.created_at %>
  </div>
<% end %>

posts_controller.rb ↓

class PostsController < ApplicationController
  def index
    @posts = Post.all
  end
end

@posts = Post.all で DB内の情報を持ってきて html に渡して、<% %> で html に埋め込む。
htmlファイルを見てみると2行目 <%= %> になっているので、@posts も表示させてしまっていたと言うことでした。
今回表示させたいのは、 post.memo と post.created_at だけだから正しくは、↓

<h1>トップページ</h1>
<% @posts.each do |post| %>
  <div>
    <%= post.memo %>
    <%= post.created_at %>
  </div>
<% end %>

まとめ

<%= %> で html に埋め込んで表示。
<% %> で html に埋め込むだけ。

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