寝て起きて寝て

プログラミングが出来ない情報系のブログ

RailsのControllerとViewをつなげるまで

コントローラーを作るには

rails generate controller name [options]

で作成できる

bundle exec 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
   create test/helpers/hello_helper_test.rb ←ビューヘルパーのテストスクリプト
   invoke assets
   invoke coffee
   create app/assets/javascripts/hello.js.coffee ←helloコントローラ固有のcoffeescript
   invoke scss
   create app/assets/stylesheets/hello.css.scss ←helloコントローラ固有のscss

以上のようなファイルが作成される

コントローラの基本構文は以下のようになる (app/controllers/hello_controller.rb)

class HelloController < ApplicationController ←クラスの継承
  def index ←アクションメソッド
    render text:'hello world' ←ここでモデルの呼び出しなど具体的な構文を記述する
  @msg = "はろーわーるど" ←テンプレート変数の値を代入

  end
end

次にviewを作っていく

railsのページは アクションメソッド(.rb)とテンプレート(.erb)2つのファイルのロジックとデザインを結合したものが出力される

なのでviewを記述する際には app/viewsフォルダ配下にviewのフォルダを作る

ファイル名は縛りがあって

コントローラ名/アクション名.html.erb

という名前で保存する必要がある

今回は「hello/view.html.erb」という名前で作成する

この名前にすることによって、Webブラウザでアクセスする際には「localhost:3000/hello/view」 という形になる

次にerbフォルダの記述をしていく(app/views/view,html.erb)

<div id = "main">
<%= @msg %>
</div>

と記述するとcontroller.rbで記述した@msgの値を呼び出せる

ちなみに controller.rbに

class HelloController < ApplicationController 
  def index
  @msg = 'はろーわーるど'
  render 'hello/special'
  end
end

と記述すると

使用するテンプレートを自由に変更することができる