일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 | 29 |
30 | 31 |
- 연습문제
- 인프런
- 자바
- 単語
- 건담베이스
- javascript
- html
- 반다이몰
- Flutter
- 디지몬
- 건담
- Web
- springboot
- ruby
- Spring
- DART
- CSS
- メソッド
- jsp
- rails7
- java
- C로 시작하는 컴퓨터 프로그래밍4판
- 一日一つメソッド
- vscode
- nico
- 일본어
- Python
- 日本語
- rails
- 비즈니스일본어
- Today
- Total
AR삽질러
初めてのRuby on Rails ControllerからViewに、Model(3) 본문
初めてのRuby on Rails ControllerからViewに、Model(3)
Controllerとviewの関係
railsでControllerの各アクションは基本的に同じ名前を持っているViewテンプレートと繋がる。
ここでは 'UsersController'の'index'アクションは自動に 'app/view/users/index.html.erb' Viewテンプレートと紐付けられる。
users_controller.rb
class UsersController < ApplicationController
def index
# @hello = "Hello World!"
@num = 10 +11
end
end
indexアクションでnumというインスタンス変数を定義する。
index.html.erb
<h1>get users Users#index</h1>
<p>Find me in app/views/users/index.html.erb</p>
<h1><%= @hello %><h1>
<p><%= @num %></p>
UsersController#index アクションに設定されている@num変数に値をHTML Pageに表紙する。
routes.rb
Rails.application.routes.draw do
# get 'users/index'
# get 'users/index', to: 'users#index'
get 'users', to: 'users#index'
end

例題
- ユーザーを管理する、Userモデルを作成する
- ユーザーは、次のデータをもつ
- 名前 name
- 年齢 age
id | name | age |
1 | arang | 20 |
2 | hana | 25 |
Modelを作成する
主なデータ型 | |
integer | 整数 |
float | 少数 |
string | 文字列 |
text | 長い文字列 |
boolean | 真偽値 |
rails g model User name:string age:integer

class CreateUsers < ActiveRecord::Migration[7.0]
def change
create_table :users do |t|
t.string :name
t.integer :age
t.timestamps
end
end
end
changeメソッド
userという新しいテーブルを生成する。
create_table :users do |t|
- ロック内のコードは、新しく生成されるテーブルのカラムを定義
t.timestamps
- created_atとupdated_atという2つのタイムスタンプカラムを自動的に生成します。 これらのカラムは、レコードが作成または更新されたときに自動的に現在の時刻を記録します。
rails db:migrate
== 20231231095816 CreateUsers: migrating ======================================
-- create_table(:users)
-> 0.0007s
== 20231231095816 CreateUsers: migrated (0.0008s) =============================
https://github.com/designAR/First_Rails_introduction/tree/CreateModel
GitHub - designAR/First_Rails_introduction
Contribute to designAR/First_Rails_introduction development by creating an account on GitHub.
github.com
'Ruby > RubyOnRails-日本語' 카테고리의 다른 글
初めてのRuby on Rails ミニQ&Aサイト開発 (0) (0) | 2023.12.31 |
---|---|
初めてのRuby on Rails データベースの確認、操作、表紙(4) (1) | 2023.12.31 |
Rails 一日一つメソッド (Day11) + form_with, link_to, each, present?メソッド (0) | 2023.12.31 |
Rails 一日一つメソッド (Day11) whereメソッド (0) | 2023.12.31 |
Rails 一日一つメソッド (Day10) before_actionメソッド (0) | 2023.12.30 |