1
2

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 5 years have passed since last update.

【Rails】0からMVC作成まで

Last updated at Posted at 2019-04-06

Railsプロジェクト作成

Railsのプロジェクトのディレクトリを作成。
mkdir フォルダ名
cd フォルダ名

Gemfileを作成。
bundle init

Gemfileを編集してRailsのバージョンを記載する。


gem 'rails', '~> 5.2.2', '>= 5.2.2.1'

bundleのパスを通してライブラリインストール。
bundle install --path vendor/bundle

rails プロジェクト作成(dbはMysqlを指定)
オプション参考サイト
bundle exec rails new --database=mysql .

必要そうなライブラリのGemfileへの記載。


\## 最低限
\# 多言語
gem 'rails-i18n'
\# 検索
gem 'ransack'
\# 認証
gem 'bcrypt'
\## slim使う場合
gem 'slim-rails'
gem 'html2slim'
\## 必要に応じて
\# オートリンク
gem 'rails_autolink'

追加ライブラリのインストール。
bundle

erbからslimへhtmlファイルを変更+erbファイル削除
bundle exec erb2slim app/views app/views -d

DBの作成
bin/rails db:create

言語設定(config/application.rb Applicationクラス内に記述)


config.i18n.default_locale = :ja

MVC構築

modelの作成

※モデル名は単数形(例:Task)
bin/rails g model モデル名 属性名:データ型 属性名:データ型 ...

viewの作成

Controllerの作成で引数に指定したアクションに対応してViewも自動生成される。

viewの書き方

フォーム


\#例
= form_with model: コントローラーのから来る変数, local: true do |オブジェクト|
        = オブジェクト.HTML属性(スネーク) :オブジェクト内の変数名
    =オブジェクト.submit 画面表示文字

\#例
= form_with model: @task, local: true do |f|
    .form-group
        = f.label :name
        = f.text_field :name, class: 'from-control', id: 'task_name'
    .form-group
        = f.label :description
        = f.text_area :description ,row:5, class: 'form-control', id: 'task_description'
    =f.submit nil, class: 'btn btn-primary'

リンク


link_to '画面表示文字', パスorURLヘルパー, class: 'クラス名'

# 例
link_to '一覧', tasks_path, class: 'nav-link'

controllerの作成

※コントローラー名は複数形(例:Tasks)
bin/rails g controller コントローラー名 アクション名 ...

簡単なCRUD実装例を記載


class TasksController < ApplicationController
  #filterの実装
  before_action :set_task, only: [:show, :edit, :update, :destroy]

  def index
    # 検索機能
    #@q = current_user.tasks.ransack(params[:q])
    #@task = @q.result(distinct: true)
    # 一覧表示
    @task = current_user.tasks.order(created_at: :desc)
  end

  def new
    @task = Task.new
  end

  def create
    @task = current_user.tasks.new(task_param)
  # DB操作(登録)
    if @task.save
  # fulashスコープに値をセット
      flash.notice = "タスク「#{@task.name}」を登録しました。"
  # リダイレクト
      redirect_to tasks_path
    else
   # 遷移元のviewを再描画
      render :new
    end
  end

  def edit
    # @task = current_user.tasks.find(params[:id])
  end

  def update
  # DB操作(更新)
  # !つけると強制的
    task.update!(task_param)
  # fulashスコープに値をセット
    flash.notice = "タスク「#{task.name}」を更新しました。"
  # リダイレクト
    redirect_to tasks_path
  end

  def destroy
    # DB操作(削除)
    task.destroy
  # fulashスコープに値をセット
    flash.notice = "タスク「#{task.name}」を削除しました。"
  # リダイレクト
    redirect_to tasks_path
  end

  # ここより下はprivate関数
  private

  def task_param
  # ストロングパラメータ
    params.require(:task).permit(:name, :description)
  end

  def set_task
  # DB操作(参照)
  # 主キーでのDBの検索(他のテーブルとリレーションあり)
    @task = current_user.tasks.find(params[:id])
  # 主キーでのDBの検索
  #@task =tasks.find(params[:id])
  end

end

ルーティング(config/routes.rb)

rootパスの設定

root to: パス

URLルーター

複数の場合
resouces : モデル名(複数形)
例:resouces : tasks

単数の場合
resouce : モデル名(単数形)
例:resouce : task

個別指定
HTTPメソッド パス , to: コントローラー名(_conrollerは省く)#アクション名
例:get '/logout', to: 'sessions#destroy'

豆知識

現在のルーティングを確認したい場合
bin/rails routes

備忘録

Migration

migrationの作成
bin/rails g migration マイグレーション名

migrationの実行
bin/rails db:migrate マイグレーション名

多言語化

例のみを記載
config/locales/xxx.ja.yml


ja:
  activerecord:
    models:
      user: ユーザー # view側: User.model_name.human => "ユーザ" / t("activerecord.models.user")と同じ
    attributes:
        user:
          id: ID
          name: 名前 # view側: User.human_attribute_name :name => "名前" / t("activerecord.attributes.user.name")と同じ
          email: メールアドレス
          admin: 管理者権限
          password_confirmation: パスワード(確認)
          created_at: 作成日
          updated_at: 更新日

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?