Ruby on Rails を触ってみる ⑦renderを使って一覧を整形
現在のツイート一覧はscaffoldで生成されたデフォルトのページのままで、非常に見づらい。ツイート一覧を表示するのが目的で、実際のTwitterのTLとは違い、自分のツイートしかないのでひとまず、①ツイート本文、②ツイート日時の2つの情報のみを表示させよう。
renderを使うのでViewファイル、_tweet.html.erbを作成する。
<div class="tweets"> <p class="tweet-text"><%= tweet.text %></p> <p class="tweet-date"><%= tweet.timestamp %></p> </div>
viewファイルtweets/index.html.erbは思い切って書き換える。
<h1>ツイート一覧</h1> <%= render(@tweets) %> <%= paginate (@tweets) %>
これだけでOK。
一度表示させてみよう。 いい感じに必要な情報だけ表示できるようになった。
twilogを参考に(笑)tweets.css.scssを少しだけ修正。
.tweets { border-bottom: 1px dotted #ccc; padding: 10px 15px 5px 20px; position: relative; .tweet-text { font-size: 108%; color: #444; line-height: 1.4; margin-bottom: 6px; word-wrap: break-word; word-break: break-all; } .tweet-date { color: #999; font-size: 13px; } }
時間の表示が日本時間ではないので修正したい。 config/application.rbにタイムゾーンの記述を追加する。
$ git diff config/application.rb # Set Time.zone default to the specified zone and make Active Record auto-convert to this zone. # Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC. - # config.time_zone = 'Central Time (US & Canada)' + config.time_zone = 'Tokyo'
しかし長ったらしい。時刻の表示フォーマットを指定しよう。 Viewファイル、tweets/_tweet.html.erbを修正。
<div class="tweets"> <p class="tweet-text"><%= tweet.text %></p> <p class="tweet-date"><%= tweet.timestamp.strftime("%Y-%m-%d %H:%M:%S") %></p> </div>