LoginSignup
2
3

More than 5 years have passed since last update.

Railsで新規アプリケーションを作成 MEMO

Posted at

はじめに

駆け出しのエンジニアがRailsで新規アプリケーションを作成しviewを表示させるまでのメモ。
hamlを使用しています。

Version

Programming歴: 70日目
Ruby: 2.3.1
Rails: 5.0.1

Step 1 - アプリケーションの作成

 

terminal
$ cd 

一旦ホームディレクトリに戻って、

terminal
$ cd projects

アプリケーションを作成・保存したいディレクトリに移動する。今回は「projects」ディレクトリにアプリケーションを作成・保存します。

terminal
$ rails new <新規アプリケーションの名前> -d mysql

「-d」はデータベースの種類を指定するオプション。今回はmysqlを用いてアプリケーションを作成します。

terminal
      create  
      create  README.md
      create  Rakefile
      create  config.ru
      ...
      ...
      ...
Use `bundle show [gemname]` to see where a bundled gem is installed.
         run  bundle exec spring binstub --all
* bin/rake: spring inserted
* bin/rails: spring inserted

ズダダダーっとterminalが走って、rails newコマンドが完了。projectsディレクトリ以下に新規アプリケーションが作成されました。

terminal
$ cd <新規アプリケーションの名前>

アプリケーションのディレクトリに移動しましょう。

terminal
$ rake db:create

データベースを作成し、

terminal
$ rails s

「rails s」コマンドでサーバーを立ち上げて、「http://localhost:3000/」 にアクセス。以下のような画像が表示されればOK!

スクリーンショット 2017-02-15 22.54.37.png

2. Model、Controller、Viewの作成と最低限のRouting

今後、「rails g」コマンドを用いてModelやControllerなどを作成していくが、
その際一緒にデフォルトで生成されてしまうhelper file、test file、assetsを生成されないように
以下のように記述を加える。(この3つは、必要になった時に手動で作れば良い、と思う。)

config.application.rb
config.generators do |g|
 g.helper false
 g.test_framework false
 g.assets false
end

●Model作成

terminal
$ rails g model <modelの名前(単数形)>

今回はまずevent modelを作りたいので、

terminal
$ rails g model event

とします。

●table作成

terminal
$ rake db:migrate

●Controller作成

terminal
$ rails g controller <Controllerの名前(複数形)>

今回はまずevent controllerを作りたいので、

terminal
$ rails g controller events

とします。

●View作成
今回viewはhamlで記述したいので、gemをインストールします。Gemfileに以下を追記し、

Gemfile
gem 'haml-rails'
gem 'erb2haml'
terminal
$ bundle install

これでhamlが使えるようになりました。

デフォルトでアプリ内にあるerbファイルをhamlに変換したいので、以下のコマンドを実行。

terminal
$ rails haml:replace_erbs

アプリ内のerbファイルをhamlに置き換えました。

その上で、app/views/eventsに、index.html.hamlを手動で作成。中に適当に文字を書きます。

app/views/events/index.html.haml
Create an app from scratch!!

●Routingの設定

config.routes.rb
Rails.application.routes.draw do
  root "events#index"
  resources :events, only: [:index]
end

このように記述。

これで、完了!

http://localhost:3000/
にアクセスすると以下のような表示になるはず。

スクリーンショット 2017-02-16 11.31.52.png

ならない場合はサーバー立ち上げ忘れの可能性あり。「rails s」を再度する。

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