LoginSignup
1
0

More than 3 years have passed since last update.

Rails ルーティングの基礎

Posted at

備忘録のために投稿。

環境

ruby 2.7.1
Rails 6.0.3.2

Rails の導入は済んでいる前提です。

generate コマンドで必要なファイルを作成

bundle exec rails g controller <controller_name> <method_name>

↓

bundle exec rails g controller home index

必要なファイルが作成される。削除したいときは delete コマンド

 bundle exec rails d controller home index

routes.rb

bundle exec rails routes

or

bundle exec rails routes | grep xxx
(絞り込み)

ディレクトリ内のルーティングの設定が見れる。

見るべきポイント

 URI Pattern                        Controller#Action
  /articles/index(.:format)         articles#index

/articles/index にアクセスすると Controller articles の Action index に飛べる。rails s でサーバ立ち上げて localhost::3000 にアクセスすれば見れる。

Rails のルールとして Controller 名はそのまま View 側の階層構造になっている。

例:HomeController(コントローラー名)

View のディレクトリ → home(ディレクトリ名)/index.html.erb(ファイル名)

Controller から View への値の渡し方

インスタンス変数を使用する

class HomesController < ApplicationController
  def index
    # インスタンス変数
    @message = "message"
  end
end

変数の前に @ を付ける事で、Controller 内で値をどこでも呼べる。View に変数の値を渡すこともできる。今回の例の場合、インスタンス変数 @message に入った文字列 "message" が渡される。

<h1>Homes#index</h1>
<%= @message %>

HTML で Ruby を呼び出したい場合、<% %> で使用できる。何か出力したい場合、<%= %> とイコールを付けると出力される。インスタンス変数 @message を渡しているので、文字列 "message" が HTML で表示される。

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