AR삽질러

初めてのRuby on Rails ルーティング、アクション、View, ERB (2) 본문

Ruby/RubyOnRails-日本語

初めてのRuby on Rails ルーティング、アクション、View, ERB (2)

아랑팡팡 2023. 12. 27. 02:20
728x90

 

初めてのRuby on Rails ルーティング、View (2)

 

1. ルーティングとは?(Rooting)

 - URLとアクションを結びつける設定のこと。

 - つまり、どんなURLがどんなControllerのどんな役割を呼び出かを決定する役割。

 - ほぼ 'config/routes.rb' Fileで定義される。

 1) Route定義

  - どんなURLがどんなControllerとアクションを紐付けるかを定義する。

  例)/users URLに入った場合 UserControllerのindexアクションが実行されるようにする。

 2) URL Parameter

  - URLに動的パラメータを追加しControllerに渡す。

  例)/users/1 URLで 1 はユーザーのIDに指定しControllerに渡してユーザーの情報を検索できる。

 3) 名前が指定されたRoot  

  - Rootに名前を指定して link_toや redirect_to とようなHelferメソッドで使うことができる。

 

2. アクションとは?(Action)

 - Controllerで実行されるメソッド・関数を意味し、ControllerはWebアプリケーションのリクエストを受けてリクエストを処理する。この時、アクションメソッドが呼ぶ出される。

 

重要なアクションメソッド
index Listを表すPageを表示する。
show 単一項目を表すPageを表示する。
new 新しい項目を作るFormを表示する。
create 新しい項目を実際に作る。
edit 既存の項目を修正するFormを表示する。
update
既存の項目を修正する。
destroy 項目を削除する。

 


rails routes : 現在定義されているすべてのRouteを表示する命令語。

users_index GET    /users/index(.:format)    users#index
Prefix Verb URL Pattern Controller
users_index GET /users/index(.:format users#index

 

 

ルーティングを変換する

Rails.application.routes.draw do
  # get 'users/index'  # http://localhost:3000/users/index
  # get 'users/index', to: 'users#index'  # http://localhost:3000/users/index
  # get 'users', to: 'users#index'  # http://localhost:3000/users
end
get 'users/index'
get 'users'
URLを指定する。 http://**/users/index
http://**/users
to: 'users#index この経路に入ってくるリクエストを処理するControllerとアクションを指定する。 users#index
 UserController
  indexアクション

 

 

 


3. Viewとは?

 - ViewはControllerからデータを受けて表示する。ControllerはModelからデータを検索、保存した後、Viewに渡す。

 

4. ERB とは?

 - Embedded Rubyの略

 - htmlの中に、 rubyのプログラムを詰め込むことができる。

 - テンプレートエンジンの一種

ERBを使うと HTML, XML もしくはmakup言語のなかにRubyコードを含めることができる。

 

ERB(Embedded Ruby) の機能

  1) Rubyコードを含む 

   - <% %>, <%= %> Tagを使ってHTMLファイルの中にRubyのコードを作成できる。

  2) 動的コンテンツを生成する

   - HTMLコンテンツを動的に変更できる。

  3) 条件文と反復文

   - Rubyの if, else, for, each などの制御文を使って複雑なロジックを作ることができる。

 

規約

 例)app/views/users/index.html.erb

 ルール)app/views/コントローラー名/アクション名.html.erb

 


routes.rb

Rails.application.routes.draw do
  # get 'users/index'
  # get 'users/index', to: 'users#index'
  get 'users', to: 'users#index'
end

 

UsersController.rb

class UsersController < ApplicationController
  def index
    # @hello = "Hello World!"
  end
end

 

index.html.erb

<h1>get users Users#index</h1>
<p>Find me in app/views/users/index.html.erb</p>

<h1><%= @hello %><h1>

<p><%= 10 + 1 %></p>

 


https://github.com/designAR/First_Rails_introduction

 

GitHub - designAR/First_Rails_introduction

Contribute to designAR/First_Rails_introduction development by creating an account on GitHub.

github.com

 

728x90
반응형
LIST