I was trying to make a simple blog application using Rails.
After I wrote all the code and content I wanted, it displays this at the end:
[#< Post id: 2, title: "Another post", body: "this is the second post", created_at: "2017-11-19 15:02:23", updated_at: "2017-11-19 15:02:23">, #<Post id: 1, title: "First post", body: "lorem ipsum", created_at: "2017-11-19 14:55:58", updated_at: "2017-11-19 14:55:58">]
(i made before 2 test posts with titles "First post" and "Another post" and with some random text on body)
And I don't how to remove this.
Here is my "routes.rb" file
Rails.application.routes.draw do
resources :posts
root "posts#index"
end
"application.html.erb":
<!DOCTYPE html>
<html>
<head>
<title>Blog</title>
<%= csrf_meta_tags %>
<%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track': 'reload' %>
<%= javascript_include_tag 'application', 'data-turbolinks-track': 'reload' %>
</head>
<body>
<div id="sidebar">
<div id="logo">
<%= link_to root_path do%>
<%= image_tag "logo.svg" %>
<% end %>
</div>
<ul>
<li class="category">Website</li>
<li><%= link_to "Blog", root_path %></li>
<li>About</li>
</ul>
<ul>
<li class="category">Social</li>
<li><a href="https://www.facebook.com/kreker71">Facebook</a></li>
<li><a href="https://github.com/Kreker71">GitHub</a></li>
<li><a href="mailto:ursache.codrut71@gmail.com">Gmail</a></li>
</ul>
</div>
<%= yield %>
</body>
</html>
"posts_controller.rb":
class PostsController < ApplicationController
def index
@posts = Post.all.order('created_at DESC')
end
def new
end
def create
@post = Post.new(post_params)
@post.save
redirect_to @post
end
def show
@post = Post.find(params[:id])
end
private
def post_params
params.require(:post).permit(:title, :body)
end
end
"index.html.erb":
<%= @posts.each do |post| %>
<div class="post_wrapper">
<h2 class="title"><%= link_to post.title, post %></h2>
<p class="date"><%= post.created_at.strftime("%B, %d, %Y") %></p>
</div>
<% end %>
"new.html.erb":
<h1>New Post</h1>
<%= form_for :post, url: posts_path do |f| %>
<p>
<%= f.label :title %><br>
<%= f.text_field :title %><br>
</p>
<p>
<%= f.label :body %><br>
<%= f.text_area :body %><br>
</p>
<p>
<%=f.submit %>
</p>
<% end %>
"show.html.erb":
<h1 class="title">
<%= @post.title %>
</h1>
<p class="date">
Submitted <%= time_ago_in_words(@post.created_at) %> Ago
</p>
<p class="body">
<%= @post.body %>
</p>
Remove the =
from <%=
on on index.html.erb
<% @posts.each do |post| %>
<div class="post_wrapper">
<h2 class="title"><%= link_to post.title, post %></h2>
<p class="date"><%= post.created_at.strftime("%B, %d, %Y") %></p>
</div>
<% end %>
Explanation: The =
is used to print some thing. So at that line you are printing the @posts
array which is what you see. Use it only if you need to output some thing.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.