LoginSignup
0
0

More than 1 year has passed since last update.

WEB開発をやり始めてみる(Rails①)

Posted at

やったこと

### コントローラーの作成
$ rails g controller Tasks

### モデルの作成
(DBのカラムを定義しています。titlestring,completedboolean型で保存されます)
$ rails g model Task title:string completed:boolean
/db/migrate/xxxxx.create.tasks.rb
### DBマイグレーションの前に下記のように修正を行う(completedはデフォルトでfalseになる)
class CreateTasks < ActiveRecord::Migration[7.0]
  def change
    create_table :tasks do |t|
      t.string :title
      t.boolean :completed, default: false

      t.timestamps
    end
  end
end
### DBに反映させる
$ rails db:migrate

### DBの中身確認
$ rails db
sqlite> .schema
CREATE TABLE "schema_migrations" ("version" varchar NOT NULL PRIMARY KEY);
CREATE TABLE "ar_internal_metadata" ("key" varchar NOT NULL PRIMARY KEY, "value" varchar, "created_at" datetime(6) NOT NULL, "updated_at" datetime(6) NOT NULL);
CREATE TABLE "tasks" ("id" integer PRIMARY KEY AUTOINCREMENT NOT NULL, "title" varchar, "completed" boolean, "created_at" datetime(6) NOT NULL, "updated_at" datetime(6) NOT NULL);
/config/routes.rb
### ルーティングの設定
(rootでアクセスするとtasks#indexコントローラーが実行ざれる)
Rails.application.routes.draw do
  # Define your application routes per the DSL in https://guides.rubyonrails.org/routing.html

  # Defines the root path route ("/")
  # root "articles#index"
  
  resources :tasks
  root 'tasks#index'
end
/app/controllers/tasks_controller.rb
### 上記のtasksコントローラーの設定を行う
(@tasksに全てのタスクを代入)
class TasksController < ApplicationController
    def index
        @tasks = Task.all
    end
end
/app/views/iendex.html.erb(新規作成)
### <%>の時は何かを実行したい時(表示させたくない)
### <%=>画面に表示させたい時
<h1>Tasksk</h1>
<ul>
    <% @tasks.each do |task| %>
        <li>
            <%= check_box_tag '','' %>
            <%= task.title %>
        </li>
    <% end %>
</ul>
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