学生向けプログラミング入門 | 無料

学生向けにプログラミングを無料で解説。Java、C++、Ruby、PHP、データベース、Ruby on Rails, Python, Django

【学習5.0】【Windows】プロジェクトとタスクモデル

プロジェクトとタスクのモデルを作成していきます。


コマンド(2つ)
rails g model Project name:string content:text price:bigint


rails g model Task title:string note:text video:string header:boolean tag:string project:references


「db\migrate\20200714234928_create_tasks.rb」ファイルに記述を追加します。


記述追加 db\migrate\20200714234928_create_tasks.rb(7行目)

t.boolean :header, null: false, default: false



db\migrate\20200714234928_create_tasks.rb

class CreateTasks < ActiveRecord::Migration[5.0]
  def change
    create_table :tasks do |t|
      t.string :title
      t.text :note
      t.string :video
      t.boolean :header, null: false, default: false
      t.string :tag
      t.references :project, foreign_key: true

      t.timestamps
    end
  end
end



コマンド マイグレーション適用
rails db:migrate


ActiveAdminに関連付けをします。


コマンド(3つ)
rails g active_admin:resource User


rails g active_admin:resource Project


rails g active_admin:resource Task


記述更新 app\admin\projects.rb

ActiveAdmin.register Project do

  permit_params :name, :content, :price, :image

end



記述更新 app\admin\tasks.rb

ActiveAdmin.register Task do

  permit_params :title, :note, :video, :header, :tag, :project_id

end



記述追加 app\models\project.rb

class Project < ApplicationRecord
    has_many :tasks

    validates :name, presence: true, length: { maximum: 50 }
    validates :content, presence: true, length: { maximum: 500 }
    validates :price, presence: true, numericality: { only_integer: true }
end



記述追加 app\models\task.rb

class Task < ApplicationRecord
  belongs_to :project

  validates :title, presence: true, length: { maximum: 50 }
  validates :video, presence: true
  validates :tag, presence: true
  validates :project, presence: true
end



ブラウザ確認
http://localhost:3000/admin/dashboard


プロジェクトを作成します。

Projectsに移動
Projectsに移動



「Projectを作成する」をクリックします。

Projectを作成
Projectを作成



項目を入力して「作成」します。

項目を入力して作成
項目を入力して作成



次にこのプロジェクトに付随するタスクを作成します。

Task作成
Task作成



作成したプロジェクトを選び、まずは「header」にチェックを入れてタスクのヘッダーを作成します。

ヘッダーの作成
ヘッダーの作成



作成したタスクヘッダーに付随するタスクも数個作成しておきます。
その場合は「header」のチェックを外します。

テスト表示用のタスクを作成
テスト表示用のタスクを作成