LoginSignup
8
9

More than 3 years have passed since last update.

[rails]Controllerを作成しよう

Last updated at Posted at 2020-07-30

Controllerを作成する

コントローラでは、ユーザーのリクエストを受けてModelと連携したり、
どの画面(View)を表示するかを制御しています。
ユーザーがURLにアクセスしたときに、リクエストを最初に受け取るのがコントローラです。
受け取ったリクエストを元にして、Modelからのデータを、対応するViewに渡して画面を表示させます。

具体的には、以下のような制御を行っています。

Modelとやり取りする
Viewに渡すインスタンス変数を定義する
表示するViewファイルを指定する

controllerを作成するのは以下を実行するだけです。
gはgenerateの略称です。

$ rails g controller コントローラ名

ただ、一つだけ注意があります。
コントローラー名は複数形になります。こんな感じです。

$ rails g controller homes

成功するとこんな感じになります。

[vagrant@localhost sample_app]$ rails g controller homes
Running via Spring preloader in process 29768
      create  app/controllers/homes_controller.rb
      invoke  erb
      create    app/views/homes
      invoke  test_unit
      create    test/controllers/homes_controller_test.rb
      invoke  helper
      create    app/helpers/homes_helper.rb
      invoke    test_unit
      invoke  assets
      invoke    coffee
      create      app/assets/javascripts/homes.coffee
      invoke    scss
      create      app/assets/stylesheets/homes.scss

間違えてControllerを作成してしまったら?

コントローラー名などを間違えて作成した場合は、以下のコマンドで消しましょう。

勘の良い人はわかるかもしれませんが、
dはdestroyを意味します。

[vagrant@localhost sample_app]$ rails d controller homes
8
9
1

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
8
9