LoginSignup
5
4

More than 3 years have passed since last update.

railsでの新規アプリケーション作成手順

Posted at

rails 5.0
例:新規投稿と一覧表示ができる簡単なアプリ開発。

1. アプリケーション作成 rails new

ターミナル
rails new アプリケーション名 -d データベースの指定

$ rails new mini-app -d mysql
$ bundle install

gemの更新

2. DB作成 rake db:create

ターミナル
ディレクトリに注意

$ rake db:create

3. modelを作成

ターミナル
post model作成

$ rails g model post

4. マイグレーションファイルにカラムを設定

qiita.rb
class CreatePosts < ActiveRecord::Migration[5.2]
  def change
    create_table :posts do |t|

      t.text :text
    end
  end
end

5. マイグレーションファイルの内容をテーブルに反映

ターミナル

$ rake db:migrate

作成したテーブルのカラムに仮データを入力

6. コントローラーを作成

ターミナル

$ rails g controller posts

7. コントローラーにアクションを指定

qiita.rb
#一覧表示
  def index 
    @posts = Post.all
  end

#新規投稿
  def new
    @post = Post.new
 end

#新規投稿の保存
  def  create
  @post  =  Post.create(text: post_params[:text])
  redirect_to root_path controller: :posts, action: :index
    #保存後、一覧に戻る
  end

  private
    def post_params
      params.require(:post).permit(:text)
    end

end

8. コントローラーのアクションに対応するviewを作成

  • view/posts/index.html.erb
  • view/posts/new.html.erb

9. ルーティングファイルにコントローラーのアクションパスを指定

qiita.rb

Rails.application.routes.draw do
  resources :posts,only: [:index,:new,:create]
end

10. rails s でサーバー立ち上げ

ターミナル

$ rails s
localhost:にアクセス
5
4
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
5
4