I was worried about formatting created_at generated by sql, so a memo of how to implement it
Create a table.
table.sql
create table todos
(
id integer PRIMARY key,
body text,
created_at
);
Use active record to bind the todos table created earlier to the object.
tlist.rb
class Todos < ActiveRecord::Base
validates :body, presence: true
end
Store the object in an instance variable.
tlist.rb
get '/' do
@todos = Todos.all
erb :index
end
Try to display the time.
index.erb
<div class="user_box">
<p class="user_name">Shuto</p>
<ul>
<% @todos.where(users_userName: "Shuto").each do |todo|%>
<li data-id = "<%= todo.id%>" data-token = "<%= Rack::Csrf.csrf_token(env)%>">
<div class="one">
<%= Rack::Utils.escape_html(todo.body)%>
</div>
<div class="time">
<%= todo.created_at%>
<span class="delete">[x]</span>
</div>
</li>
<% end%>
</ul>
</div>
When I executed it, there are unnecessary parts, so I want to format it.
After investigating, it seems that it can be formatted with the strftime method. Apply and execute the method.
index.erb
<div class="user_box">
<p class="user_name">Shuto</p>
<ul>
<% @todos.where(users_userName: "Shuto").each do |todo|%>
<li data-id = "<%= todo.id%>" data-token = "<%= Rack::Csrf.csrf_token(env)%>">
<div class="one">
<%= Rack::Utils.escape_html(todo.body)%>
</div>
<div class="time">
<%= todo.created_at.strftime("%Y/%m/%d %H:%M:%S")%>
<span class="delete">[x]</span>
</div>
</li>
<% end%>
</ul>
</div>
I was angry that it was a character string.
It seems that it is necessary to convert it to something other than a character string, so try converting it to date type.
index.erb
<div class="user_box">
<p class="user_name">Shuto</p>
<ul>
<% @todos.where(users_userName: "Shuto").each do |todo|%>
<li data-id = "<%= todo.id%>" data-token = "<%= Rack::Csrf.csrf_token(env)%>">
<div class="one">
<%= Rack::Utils.escape_html(todo.body)%>
</div>
<div class="time">
<%= todo.created_at.to_date.strftime("%Y/%m/%d %H:%M:%S")%>
<span class="delete">[x]</span>
</div>
</li>
<% end%>
</ul>
</div>
The date is correct, but the time is incorrect.
Convert it to time type and execute it.
index.erb
<div class="user_box">
<p class="user_name">Shuto</p>
<ul>
<% @todos.where(users_userName: "Shuto").each do |todo|%>
<li data-id = "<%= todo.id%>" data-token = "<%= Rack::Csrf.csrf_token(env)%>">
<div class="one">
<%= Rack::Utils.escape_html(todo.body)%>
</div>
<div class="time">
<%= todo.created_at.to_time.strftime("%Y/%m/%d %H:%M:%S")%>
<span class="delete">[x]</span>
</div>
</li>
<% end%>
</ul>
</div>
It was displayed properly.
You need to find out what format it is given when you face an error.
The prototype of this application is based on Introduction to sinatra of dot installation.
Recommended Posts