0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Windows10でRuby on Railsのコントローラを作ってhtmlを表示した

Posted at

説明

初めてのRuby on Railsです。
前回の続きでコントローラを作ってhtmlを表示します。
(Markdownの書き方も勉強中です。)

環境

モノ バージョン
OS Windows10 Home(64bit)
Ruby 2.2.6
Rails 5.0.2
エディタ Visual Studio Code

コントローラを作る

helloというコントローラをコマンドから作成する

rails generate controller hello
      create  app/controllers/hello_controller.rb
      invoke  erb
      create    app/views/hello
      invoke  test_unit
      create    test/controllers/hello_controller_test.rb
      invoke  helper
      create    app/helpers/hello_helper.rb
      invoke    test_unit
      invoke  assets
      invoke    coffee
      create      app/assets/javascripts/hello.coffee
      invoke    scss
      create      app/assets/stylesheets/hello.scss

いろいろできた。invokeは翻訳すると「呼び出す」らしい。
よくわからないが次へ。

作ったコントローラに手を加える

indexという名前のメソッド(def)を追加して、その中ではhtmlを返すのだ。

\hogehoge\app\controllers\hello_controller.rb
class HelloController < ApplicationController
    def index
        myhtml = '
        <html>
        <body>
        <h1>I think that I am on Rails!</h1>
        </body>
        </html>'
        render html: myhtml.html_safe
    end
end

ルーティング定義(routes.rb)を追加する

helloにアクセスしたら、helloControlのindexを呼び出してくださいという追加。

\hogehoge\config\routes.rb
Rails.application.routes.draw do
  # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
  get 'hello', to: 'hello#index'
end

ブラウザで確認してみる

でた!
20170402_001.png

ログからもHelloControllerのindexが処理されていることが読み取れる。

\hogehoge\log\development.log
Started GET "/hello" for ::1 at 2017-04-02 18:35:15 +0900
Processing by HelloController#index as HTML
  Rendering html template
  Rendered html template (0.0ms)
Completed 200 OK in 4ms (Views: 1.4ms | ActiveRecord: 0.0ms)

ここまで。続きはまた次回。


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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?