0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

コマンド打ち込みで簡単に静的なページの作成と削除

Last updated at Posted at 2021-11-21

ほぼ静的なページを用意するのに必要なもの

1.view

2.router

3.controller

4.cssやjavascript

このように静的なページを用意するにも非常に作成しなければならないファイルが多い。もちろん手動で作成することも可能だがrailsにはこのようなファイルを一括で用意してくれるコマンドが用意されている。
以下にrailsで使用する事ができるコマンドラインツールが紹介されたページを貼っておく

静的なページを作成するために以下のコマンドを入力する

$ docker-compose run web rails generate controller ControllerName action1 action2

dockerを使っているので以上のようなコマンドになるがIDEや仮想コンテナを使用しないケースではrails以下を打ち込めば問題ないだろう

またrails generate は rails gでも同様に動作する。

$ docker-compose run web rails g controller ControllerName action1 action2

1.view

viewsの中に新たに スネークケースで書かれたfolderが用意されさらに、そこにaction1,action2で指定した名前のファイルが用意されている。

スクリーンショット 2021-11-21 15.47.20.png

2.router

config fileの中のroutes.rbにこのような記述になっている

Rails.application.routes.draw do
  get 'static_pages/home'
  get 'static_pages/help'
  
end

localhost:3000/static_pages/homeのようにrouterが設定されている。static_page/homeはパスとしてダサいのでおそらく変えないといけないが笑

3.controller

controllersに指定した名前のコントローラ名でfileが作成されている

class StaticPagesController < ApplicationController
  def home
  end

  def help
  end
end

4.cssやjs

assetsの中のstylesheetやjavascriptに以下のようなfileが用意されていた。

scssの例

// Place all the styles related to the StaticPages controller here.
// They will automatically be included in application.css.
// You can use Sass (SCSS) here: http://sass-lang.com/

作ったfileやfolderを一括で削除する。

これについても一つ一つ確認しながら消す必要はない

$ docker-compose run web rails destroy controller ControllerName action1 action2

または

$ docker-compose run web rails d controller ControllerName action1 action2

このコマンドを実行することでさっき作成したファイルやフォルダを一括で削除してくれる。いらなくなったケースやコントローラの名前を変えたくなったケースに利用したい。消すともちろんのことだが、書いたものはリセットされるので名前を変えたいケースは注意したい。

最後に

コマンド操作で簡単に静的ページの作成と削除ができることがわかった。destroyというと壊すというイメージがあるので少しコマンドをうつのこわい気がするが、railsではdestroyは削除するという意味で色々なところで使われるみたい

参考にした記事

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?