イテレーションC1:カタログリストの作成
今度はお客様の支払いに関するコントローラーを作成します。
depot> rails generate controller Store index
webサイトにアクセスしやすくなるようにrootのURLを設定する
/depot/config/routes.rb
Rails.application.routes.draw do get "store/index" resource :products #ルートパスにstoreコントローラーのindexメソッドを設定 #as:'store'でstore_pathメソッド追加 root to: 'store#index', as : 'store' end
動作確認用のpublic/index.htmlを使わなくなるので、削除
depot> rm public/index.html
rails4ではないのか、ファイルは見当たらなかったので、上記は未実施。
DBから商品リストを取り出し、ビューへ渡す。
class StoreController < ApplicationController def index @products = Product.order(:title) end end
ルートパスで起動するStoreController#indexにおいて
Productオブジェクトからデータを取り出す。
取り出す順序をorderで指定。
orderへの引数の指定の仕方
■ハッシュ
:title (昇順)
■文字列
"title" (昇順)
"title ASC" (昇順)
"title DESC" (降順)
商品リストのビューを作成する
<h1>Programticカタログ</h1> <% @products.each do |product| %> <div class="entry"> <%= image_tag(product.image_url) %> <h3><%= product.title %></h3> <%= sanitize(product.description) %> <div class="price_line"> <span class="price"><%= product.price %></span> </div> </div> <% end %>
StoreControllerで指定した@productsを用い、
商品をリスト表示している。
sanitize()を用いることで引数内の欄にHTMLタグを含めることができるようになる。
セキュリティーホールとなるが、ユーザーは社内の人間が想定し、危険性が少ない
との判断で、この関数を用いている。
イテレーションC2:ページレイアウトを追加
application.htmlを編集することにより
アプリケーション全体のレイアウトを整えます。
<html> <head> <title>Progprog Booksオンラインストア</title> <%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track' => true %> <%= javascript_include_tag 'application', 'data-turbolinks-track' => true %> <%= csrf_meta_tags %> </head> <body class='<%= controller.controller_name %>'> ・・・ <div> <%= yield %> </div> </body> </html>
csrf_meta_tagsはクロスサイトフォージェリ(CSRF)を防ぐための仕組みらしい。
CSRF:webサイトにスクリプトを埋め込み、閲覧者に意図せず別のサイト上の何らかの
操作を行わせる攻撃手法
<%= yield %>
の部分でそれぞれのコンテンツを呼び出す。
カタログページのレイアウトを整えるために以下を作成する
/depot/app/assets/stylesheets/layouts.css.scss
stylesheets以下に配置したcssはapplication.cssによって読み込まれる。
application.css内のrequire_treeという記述によって実現。
8.4 イテレーションC4: コントローラの機能テスト
モデル、ビュー、コントローラが正しく連携していることのテストを作成する。
require 'test_helper' class StoreControllerTest < ActionController::TestCase test "should get index" do get :index assert_response :success #第一パラメータが最低4つあるか assert_select '#columns #side a', minimum: 4 #第一パラメータが3つあるか assert_select '#main .entry', 3 #第一パラメータの要素の内容が第二パラメータの値であるか assert_select 'h3', 'Programming Ruby 1.9' #第一パラメータが第二パラメータの正規表現にマッチするか assert_select '.price', /\$[,\d]+\.\d\d/ end end
■自由課題
・サイドバーに日付と時刻を追加する
日本語のタイムゾーンに変更する(rails4)
application.rb
# 表示時のタイムゾーンをJSTに変更 config.time_zone = 'Tokyo'
store_controller.rb
class StoreController < ApplicationController def index ・・・ @time = Time.now() end end
view/store/index.html.erb
<div id="time"><%= @time.to_s(:db) %></div>
.to_s(:db)で「%Y-%m-%d %H:%M:%S"」の形式で表示
参考:http://d.hatena.ne.jp/zariganitosh/20080809/1218241507
画面で色が見えないので色も変更。
layouts.css.scss
#side { ・・・ #time { color: #f0f0f0 } }
8章完了。次はカート作成