LoginSignup
3
0

More than 5 years have passed since last update.

rails でページを作成する

Posted at

LPで今までは中身のコーディングだけだったものの、自分で初めてページを生成することになり少しrailsについて勉強。

railsでページを表示するために

  • view
  • Controller
  • アクション
  • routing

上記4つの作成が必要。

まず最初に

terminalで下記コマンドを実行

rails generate controller コントローラ名

色々ファイルが生成される。

viewの作成

ブラウザからリクエストが飛んできてルーティング→コントローラーが受ける。
その後どのviewを表示させるのかコントローラが決め、表示させる。
viewはviewsフォルダに置かれている。html,erbが多い。
app/viewsの中に格納されている。
ファイル名は(アクション名).html.erb」とする

image.png

ファイル内にテストで書いてみる

index.html.erb
<div>
 hello world!
</div>

Controllerの作成

Controllerファイルはapp/controllersの中に格納されている。
image.png

アクションの作成

Railsアプリケーションではコントローラはクラスとして定義されたが、
アクションはコントローラクラスの中のメソッドとして定義される。

hello_controlloer.rb
class HelloController < ApplicationController
  def index
  end
end

routingの設定

ルーティングはURLのリクエストが飛んだ際にどのコントローラのどのアクションを行うかを決める箇所。
config/routes.rbが対応箇所になる。

routes.rb
Rails.application.routes.draw do
 get '/hello' to: 'hello#index'
end
# get URL => "コントローラ名#アクション名"

これで
http://localhost:3000/hello
image.png

で開くとページの確認ができる!

3
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
3
0