0
0

More than 3 years have passed since last update.

Railsチュートリアル備忘録(3章 3.3.2)

Last updated at Posted at 2020-12-25

環境

macOS Catalina 10.15.5
Rails 6.0.3

Railsチュートリアルとそれに付随するいろいろを書いていきます。
Githubに慣れたいので、チュートリアルは第6版に準拠しています。

3.3.2 Red

/static_pages/aboutというURLからビューを表示させたい。
$ rails tからどのような順番で確認していくか?

結論

config/routes.rbにURLを作る
app/controllers/static_pages_controller.rbにaboutアクションを作る
app/views/static_pagesabout.html.erb(ビュー)を作成する

概要

test追加

test/controllers/static_pages_controller_test.rb
test "should get about" do
    get static_pages_about_url
    assert_response :success
  end
end


$ rails t

NameError: undefined local variable or method `static_pages_about_url'

「`static_pages_about_url'(URL)が見つからない」


routes.rbにURLを作る

config/routes.rb
get  'static_pages/about'

(/static_pages/aboutというURLに対してGETリクエストが来たら、StaticPagesコントローラのaboutアクションに渡す)

$ rails t

AbstractController::ActionNotFound:
The action 'about' could not be found for StaticPagesController

「StaticPagesコントローラにaboutアクションがない」


static_pages_controller.rbにaboutアクションを作る

app/controllers/static_pages_controller.rb
def about
end


$ rails t

ActionController::MissingExactTemplate: 
StaticPagesController#about is missing a template for request formats: text/html

StaticPagesControlleraboutのテンプレートが無い」


app/views/static_pagesabout.html.erbを作成する
(テンプレート=views内のデータ なので、例えばaboutアクションはabout.html.erbというビューに関連付けられるため。
今回はstatic_pagesに関するビューなので該当のフォルダに置く)

$ touch app/views/static_pages/about.html.erbを実行するとファイルが作成されました。

$ rails t
結果は green になりました。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0