前回の記事「Railsでモデルを作成する」で、モデルは作成済み。
ビューとコントローラは、「Railsでアプリケーションを実装してみる」で作成したものを流用する。
ルーティング
config\routes.rbを下記のように書き換える。
Rails.application.routes.draw do get 'hello_cats/index', to: 'hello_cats#index' resources :articles root 'hello_cats#index' end
該当URLとHTTPメソッドのGETがブラウザからリクエストされたら、hello_cats_controllerのindexアクションを実行する。
コントローラ
今は空っぽだけど、このindexメソッドの中に処理を追加していく。
app/controllers/hello_cats_controller.rbを下記のように編集。
class HelloCatsController > ApplicationController def index @catsinfo = CatsInfo.all end end
データベースのデータを全て取得して、catsinfoに入れる。
ビュー
次に見栄えの変更。
app/view/hello_cats/index.html.erb
<h1>HelloCats!!</h1> <p>ネコのブログ</p> <img src="/assets/Shima.png"> <table> <tr> <th>Name</th> <th>Age</th> <th>Color</th> </tr> <% @catsinfo.each do |info| %> <tr> <td><%= info.name %></td> <td><%= info.age %></td> <td><%= info.color %></td> </tr> <% end %> </table>
HTMLの中にRubyのコードを埋め込みたい時は、<% %>と書くと、実行される。
実行結果を表示したい場合は、<%= %>と書くことで、実行後の結果も表示される。
変更内容を保存して、rails sコマンドでサーバーを起動したら、http://localhost:3000/hello_cats/indexにアクセスする。
モデルのデータをコントローラで引っぱってきて、ビューで成形した表の形で表示させることに成功。
誕生日も表示できるようにしてみた。
app/view/hello_cats/index.html.erb
<h1>HelloCats!!</h1> <p>ネコのブログ</p> <img src="/assets/Shima.png"> <table> <tr> <th>Name</th> <th>Age</th> <th>Birthday</th> <th>Color</th> </tr> <% @catsinfo.each do |info| %> <tr> <td><%= info.name %></td> <td><%= info.age %></td> <td><%= info.year %>年<%= info.month %>月<%= info.date %>日</td> <td><%= info.color %></td> </tr> <% end %> </table>
イイ感じ。