갈루아의 반서재




레일즈 프로젝트 만들기


blog 어플리케이션을 만듭니다. 다음과 같이 blog 라고 하는 레일즈 어플리케이션을 blog 디렉토리에 만듭니다.

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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
root@localhost:~# rails new blog
      create
      create  README.md
      create  Rakefile
      create  config.ru
      create  .gitignore
      create  Gemfile
         run  git init from "."
초기화: 빈 깃 저장소, 위치 /root/blog/.git/
      create  app
      create  app/assets/config/manifest.js
      create  app/assets/javascripts/application.js
      create  app/assets/javascripts/cable.js
      create  app/assets/stylesheets/application.css
      create  app/channels/application_cable/channel.rb
      create  app/channels/application_cable/connection.rb
      create  app/controllers/application_controller.rb
      create  app/helpers/application_helper.rb
      create  app/jobs/application_job.rb
      create  app/mailers/application_mailer.rb
      create  app/models/application_record.rb
      create  app/views/layouts/application.html.erb
      create  app/views/layouts/mailer.html.erb
      create  app/views/layouts/mailer.text.erb
      create  app/assets/images/.keep
      create  app/assets/javascripts/channels
      create  app/assets/javascripts/channels/.keep
      create  app/controllers/concerns/.keep
      create  app/models/concerns/.keep
      create  bin
      create  bin/bundle
      create  bin/rails
      create  bin/rake
      create  bin/setup
      create  bin/update
      create  bin/yarn
      create  config
      create  config/routes.rb
      create  config/application.rb
      create  config/environment.rb
      create  config/secrets.yml
      create  config/cable.yml
      create  config/puma.rb
      create  config/spring.rb
      create  config/environments
      create  config/environments/development.rb
      create  config/environments/production.rb
      create  config/environments/test.rb
      create  config/initializers
      create  config/initializers/application_controller_renderer.rb
      create  config/initializers/assets.rb
      create  config/initializers/backtrace_silencers.rb
      create  config/initializers/cookies_serializer.rb
      create  config/initializers/cors.rb
      create  config/initializers/filter_parameter_logging.rb
      create  config/initializers/inflections.rb
      create  config/initializers/mime_types.rb
      create  config/initializers/new_framework_defaults_5_1.rb
      create  config/initializers/wrap_parameters.rb
      create  config/locales
      create  config/locales/en.yml
      create  config/boot.rb
      create  config/database.yml
      create  db
      create  db/seeds.rb
      create  lib
      create  lib/tasks
      create  lib/tasks/.keep
      create  lib/assets
      create  lib/assets/.keep
      create  log
      create  log/.keep
      create  public
      create  public/404.html
      create  public/422.html
      create  public/500.html
      create  public/apple-touch-icon-precomposed.png
      create  public/apple-touch-icon.png
      create  public/favicon.ico
      create  public/robots.txt
      create  test/fixtures
      create  test/fixtures/.keep
      create  test/fixtures/files
      create  test/fixtures/files/.keep
      create  test/controllers
      create  test/controllers/.keep
      create  test/mailers
      create  test/mailers/.keep
      create  test/models
      create  test/models/.keep
      create  test/helpers
      create  test/helpers/.keep
      create  test/integration
      create  test/integration/.keep
      create  test/test_helper.rb
      create  test/system
      create  test/system/.keep
      create  test/application_system_test_case.rb
      create  tmp
      create  tmp/.keep
      create  tmp/cache
      create  tmp/cache/assets
      create  vendor
      create  vendor/.keep
      create  package.json
      remove  config/initializers/cors.rb
      remove  config/initializers/new_framework_defaults_5_1.rb
         run  bundle install
 
Bundle complete! 16 Gemfile dependencies, 70 gems now installed.
Use `bundle info [gemname]` to see where a bundled gem is installed.
         run  bundle exec spring binstub --all
* bin/rake: spring inserted
* bin/rails: spring inserted
cs


레일즈 어플리케이션에 대한 모든 옵션들은 다음과 같이 확인할 수 있습니다.

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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
root@localhost:~# rails new -h
Usage:
  rails new APP_PATH [options]
 
Options:
  -r, [--ruby=PATH]                                      # Path to the Ruby binary of your choice
                                                         # Default: /root/.rbenv/versions/2.4.1/bin/ruby
  -m, [--template=TEMPLATE]                              # Path to some application template (can be a filesystem path or URL)
  -d, [--database=DATABASE]                              # Preconfigure for selected database (options: mysql/postgresql/sqlite3/oracle/frontbase/ibm_db/sqlserver/jdbcmysql/jdbcsqlite3/jdbcpostgresql/jdbc)
                                                         # Default: sqlite3
      [--skip-yarn], [--no-skip-yarn]                    # Don't use Yarn for managing JavaScript dependencies
      [--skip-gemfile], [--no-skip-gemfile]              # Don't create a Gemfile
  -G, [--skip-git], [--no-skip-git]                      # Skip .gitignore file
      [--skip-keeps], [--no-skip-keeps]                  # Skip source control .keep files
  -M, [--skip-action-mailer], [--no-skip-action-mailer]  # Skip Action Mailer files
  -O, [--skip-active-record], [--no-skip-active-record]  # Skip Active Record files
  -P, [--skip-puma], [--no-skip-puma]                    # Skip Puma related files
  -C, [--skip-action-cable], [--no-skip-action-cable]    # Skip Action Cable files
  -S, [--skip-sprockets], [--no-skip-sprockets]          # Skip Sprockets files
      [--skip-spring], [--no-skip-spring]                # Don't install Spring application preloader
      [--skip-listen], [--no-skip-listen]                # Don't generate configuration that depends on the listen gem
      [--skip-coffee], [--no-skip-coffee]                # Don't use CoffeeScript
  -J, [--skip-javascript], [--no-skip-javascript]        # Skip JavaScript files
      [--skip-turbolinks], [--no-skip-turbolinks]        # Skip turbolinks gem
  -T, [--skip-test], [--no-skip-test]                    # Skip test files
      [--skip-system-test], [--no-skip-system-test]      # Skip system test files
      [--dev], [--no-dev]                                # Setup the application with Gemfile pointing to your Rails checkout
      [--edge], [--no-edge]                              # Setup the application with Gemfile pointing to Rails repository
      [--rc=RC]                                          # Path to file containing extra configuration options for rails command
      [--no-rc], [--no-no-rc]                            # Skip loading of extra configuration options from .railsrc file
      [--api], [--no-api]                                # Preconfigure smaller stack for API only apps
  -B, [--skip-bundle], [--no-skip-bundle]                # Don't run bundle install
      [--webpack=WEBPACK]                                # Preconfigure for app-like JavaScript with Webpack (options: react/vue/angular)
 
Runtime options:
  -f, [--force]                    # Overwrite files that already exist
  -p, [--pretend], [--no-pretend]  # Run but do not make any changes
  -q, [--quiet], [--no-quiet]      # Suppress status output
  -s, [--skip], [--no-skip]        # Skip files that already exist
 
Rails options:
  -h, [--help], [--no-help]        # Show this help message and quit
  -v, [--version], [--no-version]  # Show Rails version number and quit
 
Description:
    The 'rails new' command creates a new Rails application with a default
    directory structure and configuration at the path you specify.
 
    You can specify extra command-line arguments to be used every time
    'rails new' runs in the .railsrc configuration file in your home directory.
 
    Note that the arguments specified in the .railsrc file don't affect the
    defaults values shown above in this help message.
Example:
    rails new ~/Code/Ruby/weblog
    This generates a skeletal Rails installation in ~/Code/Ruby/weblog.
cs


blog 폴더로 이동합니다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
root@localhost:~# cd blog
root@localhost:~/blog# ls -al
합계 84
drwxr-xr-13 root root 4096  7월 17 13:07 .
drwx--x--61 root root 4096  7월 17 13:06 ..
drwxr-xr-x  7 root root 4096  7월 17 13:06 .git
-rw-r--r--  1 root root  536  7월 17 13:06 .gitignore
-rw-r--r--  1 root root 1974  7월 17 13:06 Gemfile
-rw-r--r--  1 root root 4774  7월 17 13:07 Gemfile.lock
-rw-r--r--  1 root root  374  7월 17 13:06 README.md
-rw-r--r--  1 root root  227  7월 17 13:06 Rakefile
drwxr-xr-10 root root 4096  7월 17 13:06 app
drwxr-xr-x  2 root root 4096  7월 17 13:07 bin
drwxr-xr-x  5 root root 4096  7월 17 13:06 config
-rw-r--r--  1 root root  130  7월 17 13:06 config.ru
drwxr-xr-x  2 root root 4096  7월 17 13:06 db
drwxr-xr-x  4 root root 4096  7월 17 13:06 lib
drwxr-xr-x  2 root root 4096  7월 17 13:06 log
-rw-r--r--  1 root root   62  7월 17 13:06 package.json
drwxr-xr-x  2 root root 4096  7월 17 13:06 public
drwxr-xr-x  9 root root 4096  7월 17 13:06 test
drwxr-xr-x  3 root root 4096  7월 17 13:06 tmp
drwxr-xr-x  2 root root 4096  7월 17 13:06 vendor
cs


blog 어플리케이션내의 폴더와 파일의 주요 기능은 다음과 같습니다.

파일/폴더 목적

Gemfile

이 파일은 여러분의 레일즈 어플리케이션에게 필요한 젬의 의존성 정보를 기술하는데 사용됩니다.

README

이 파일은 어플리케이션을 위한 짧막한 설명입니다. 설치, 사용 방법 기술에 쓰입니다.

Rakefile

이 파일은 터미널에서 실행할 수 있는 배치잡들을 포함합니다.

app/

어플리케이션을 위한 컨트롤러, 모델, 뷰를 포함합니다. 이 가이드에서는 이 폴더에 집중할 것 입니다.

config/

어플리케이션의 실행 시간의 규칙, 라우팅, 데이터베이스 등 설정을 저장합니다.

config.ru

랙(Rack) 기반의 서버들이 시작할때 필요한 설정 입니다.

db/

현재 데이터베이스의 스키마를 볼 수 있습니다.(데이터베이스 마이그레이션으로 잘 알려져 있습니다.) 여러분은 마이그레이션에 대해서 간단하게 배우게 됩니다.

doc/

어플리케이션에 대한 자세한 설명 문서입니다.

lib/

어플리케이션을 위한 확장 모듈입니다. (이 문서에서 다루지 않습니다.)

log/

어플리케이션의 로그 파일입니다.

public/

외부에서 볼수 있는 유일한 폴더 입니다.이미지, 자바스크립트, 스타일시트나 그외 정적인 파일들은 이곳에 두세요.

script/

레일즈 스크립트를 포함합니다. 여러분의 어플리케이션을 실행시키거나, 배포, 실행 관련한 스크립트를 두세요.

test/

유닛 테스트, 픽스쳐, 그와 다른 테스트 도구들 입니다. 이 부분은 레일즈 어플리케이션 테스트하기 가 담당합니다.

tmp/

Temporary files

tmp/

임시 파일

vendor/

서드 파티 코드들을 위한 공간입니다. 일반적인 레일즈 어플리케이션은 루비 젬과 레일즈 소스-프로젝트 내에 설치시-와 미리 패키징된 추가 플러그인들이 위치합니다.


레일즈 어플리케이션은 gem 의 의존성을 기본적으로 Bunlder를 통해서 관리합니다. 다음의 명령을 통해 필요한 gem 을 설치합니다.

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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
root@localhost:~/blog# bundle install
Don't run Bundler as root. Bundler can ask for sudo if it is needed, and installing your bundle as root will break this application
for all non-root users on this machine.
Using rake 12.0.0
Using concurrent-ruby 1.0.5
Using i18n 0.8.6
Using minitest 5.10.2
Using thread_safe 0.3.6
Using builder 3.2.3
Using erubi 1.6.1
Using mini_portile2 2.2.0
Using rack 2.0.3
Using nio4r 2.1.0
Using websocket-extensions 0.1.2
Using mime-types-data 3.2016.0521
Using arel 8.0.0
Using method_source 0.8.2
Using thor 0.19.4
Using bundler 1.15.1
Using sqlite3 1.3.13
Using puma 3.9.1
Using rb-fsevent 0.10.2
Using ffi 1.9.18
Using tilt 2.0.7
Using execjs 2.7.0
Using coffee-script-source 1.12.2
Using turbolinks-source 5.0.3
Using multi_json 1.12.1
Using byebug 9.0.6
Using public_suffix 2.0.5
Using rubyzip 1.2.1
Using bindex 0.5.0
Using ruby_dep 1.5.0
Using tzinfo 1.2.3
Using nokogiri 1.8.0
Using rack-test 0.6.3
Using sprockets 3.7.1
Using websocket-driver 0.6.5
Using mime-types 3.1
Using rb-inotify 0.9.10
Using childprocess 0.7.1
Using uglifier 3.2.0
Using coffee-script 2.4.1
Using turbolinks 5.0.1
Using addressable 2.5.1
Using activesupport 5.1.2
Using loofah 2.0.3
Using xpath 2.1.0
Using mail 2.6.6
Using sass-listen 4.0.0
Using listen 3.1.5
Using selenium-webdriver 3.4.4
Using rails-dom-testing 2.0.3
Using globalid 0.4.0
Using activemodel 5.1.2
Using jbuilder 2.7.0
Using spring 2.0.2
Using rails-html-sanitizer 1.0.3
Using capybara 2.14.4
Using sass 3.5.1
Using activejob 5.1.2
Using activerecord 5.1.2
Using spring-watcher-listen 2.0.1
Using actionview 5.1.2
Using actionpack 5.1.2
Using actioncable 5.1.2
Using actionmailer 5.1.2
Using railties 5.1.2
Using sprockets-rails 3.2.0
Using coffee-rails 4.2.2
Using web-console 3.5.1
Using rails 5.1.2
Using sass-rails 5.0.6
Bundle complete! 16 Gemfile dependencies, 70 gems now installed.
Use `bundle info [gemname]` to see where a bundled gem is installed.
cs



데이터베이스 설정


데이터페이스의 사용하기 위해서 config/database.yml 설정 파일이 필요합니다. 아래에서 보시다시피 SQLite3 가 기본 데이터베이스로 설정되어 있으며, 아래와 같이 development, test, production 이상 3가지의 환경 설정으로 구성되어 있습니다.

/root/blog/config/database.yml

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
# SQLite version 3.x
#   gem install sqlite3
#
#   Ensure the SQLite 3 gem is defined in your Gemfile
#   gem 'sqlite3'
#
default: &default
  adapter: sqlite3
  pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %>
  timeout: 5000
 
development:
  <<*default
  database: db/development.sqlite3
 
# Warning: The database defined as "test" will be erased and
# re-generated from your development database when you run "rake".
# Do not set this db to the same as development or production.
test:
  <<*default
  database: db/test.sqlite3
 
production:
  <<*default
  database: db/production.sqlite3
cs


rake 명령어로 데이터베이스를 생성합니다. 개발과 테스트를 위한 SQLite3 데이터베이스를 db 폴더에 만들게 됩니다.

1
2
3
root@localhost:~/blog# rake db:create
Created database 'db/development.sqlite3'
Created database 'db/test.sqlite3'
cs


rake -T 명령어로 실행할 수 있는 rake 명령어를 확인할 수 있습니다.

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
32
33
34
35
36
37
38
39
40
41
42
43
root@localhost:~/blog# rake -T
rake about                              # List versions of all Rails frameworks and the environment
rake app:template                       # Applies the template supplied by LOCATION=(/path/to/template) or URL
rake app:update                         # Update configs and some other initially generated files (or use just update:configs or...
rake assets:clean[keep]                 # Remove old compiled assets
rake assets:clobber                     # Remove compiled assets
rake assets:environment                 # Load asset compile environment
rake assets:precompile                  # Compile all the assets named in config.assets.precompile
rake cache_digests:dependencies         # Lookup first-level dependencies for TEMPLATE (like messages/show or comments/_comment....
rake cache_digests:nested_dependencies  # Lookup nested dependencies for TEMPLATE (like messages/show or comments/_comment.html)
rake db:create                          # Creates the database from DATABASE_URL or config/database.yml for the current RAILS_EN...
rake db:drop                            # Drops the database from DATABASE_URL or config/database.yml for the current RAILS_ENV ...
rake db:environment:set                 # Set the environment value for the database
rake db:fixtures:load                   # Loads fixtures into the current environment's database
rake db:migrate                         # Migrate the database (options: VERSION=x, VERBOSE=false, SCOPE=blog)
rake db:migrate:status                  # Display status of migrations
rake db:rollback                        # Rolls the schema back to the previous version (specify steps w/ STEP=n)
rake db:schema:cache:clear              # Clears a db/schema_cache.yml file
rake db:schema:cache:dump               # Creates a db/schema_cache.yml file
rake db:schema:dump                     # Creates a db/schema.rb file that is portable against any DB supported by Active Record
rake db:schema:load                     # Loads a schema.rb file into the database
rake db:seed                            # Loads the seed data from db/seeds.rb
rake db:setup                           # Creates the database, loads the schema, and initializes with the seed data (use db:res...
rake db:structure:dump                  # Dumps the database structure to db/structure.sql
rake db:structure:load                  # Recreates the databases from the structure.sql file
rake db:version                         # Retrieves the current schema version number
rake dev:cache                          # Toggle development mode caching on/off
rake initializers                       # Print out all defined initializers in the order they are invoked by Rails
rake log:clear                          # Truncates all/specified *.log files in log/ to zero bytes (specify which logs with LOG...
rake middleware                         # Prints out your Rack middleware stack
rake notes                              # Enumerate all annotations (use notes:optimize, :fixme, :todo for focus)
rake notes:custom                       # Enumerate a custom annotation, specify with ANNOTATION=CUSTOM
rake restart                            # Restart app by touching tmp/restart.txt
rake routes                             # Print out all defined routes in match order, with names
rake secret                             # Generate a cryptographically secure secret key (this is typically used to generate a s...
rake stats                              # Report code statistics (KLOCs, etc) from the application or engine
rake test                               # Runs all tests in test folder except system ones
rake test:db                            # Run tests quickly, but also reset db
rake test:system                        # Run system tests only
rake time:zones[country_or_offset]      # List all time zones, list by two-letter country code (`rails time:zones[US]`), or list...
rake tmp:clear                          # Clear cache and socket files from tmp/ (narrow w/ tmp:cache:clear, tmp:sockets:clear)
rake tmp:create                         # Creates tmp directories for cache, sockets, and pids
rake yarn:install                       # Install all JavaScript dependencies as specified via Yarn
cs


Hello, Rails!


다음과 같이 웹서버를 시작합니다.

1
2
3
4
5
6
7
8
9
10
root@localhost:~/blog# rails server
=> Booting Puma
=> Rails 5.1.2 application starting in development on http://localhost:3000
=> Run `rails server -h` for more startup options
Puma starting in single mode...
* Version 3.9.1 (ruby 2.4.1-p111), codename: Private Caller
* Min threads: 5, max threads: 5
* Environment: development
* Listening on tcp://0.0.0.0:3000
Use Ctrl-C to stop
cs

브라우저를 실행해서 http://localhost:3000 에 접속해, 레일즈의 기본 정보 페이지를 볼 수 있습니다.


레일즈가 "Hello"라고 말하게 하려면, 최소한 컨트롤러와 뷰정도는 만들어야 합니다. 다행스럽게도, 명령어 한줄이면 충분합니다. 다음의 명령어를 터미널에서 입력하세요.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
root@localhost:~/blog# rails generate controller home index
Running via Spring preloader in process 14789
      create  app/controllers/home_controller.rb
       route  get 'home/index'
      invoke  erb
      create    app/views/home
      create    app/views/home/index.html.erb
      invoke  test_unit
      create    test/controllers/home_controller_test.rb
      invoke  helper
      create    app/helpers/home_helper.rb
      invoke    test_unit
      invoke  assets
      invoke    coffee
      create      app/assets/javascripts/home.coffee
      invoke    scss
      create      app/assets/stylesheets/home.scss
cs


레일즈는 app/views/home/index.html.erb 포함해서 몇가지 파일을 만들겁니다. 아 파일은 home 컨트롤러의 index 액션을 위한 템플릿으로 이용됩니다.

/root/blog/app/controllers/home_controller.rb

1
2
3
4
class HomeController < ApplicationController
  def index
  end
end
cs

/root/blog/app/views/home/index.html.erb

1
2
<h1>Home#index</h1>
<p>Find me in app/views/home/index.html.erb</p>
cs

상기 파일을 다음과 같이 수정합니다.

1
<h1>Hello, Rails!</h1> 
cs


앞서 컨트롤러와 뷰를 만들었고, 이제 브라우저에 “Hello Rails”를 출력하기 위해 레일즈에게 요청을 할 차례입니다. 홈페이지의 위치를 레일즈에게 알려주어야 합니다.

config/routes.rb 를 수정합니다. 이 파일은 외부 요청과 컨트롤러와 액션을 연결하는 방법이 기술된 어플리케이션의 라우팅 파일 입니다.

/root/blog/config/routes.rb

1
2
3
4
Rails.application.routes.draw do
  get 'home/index'
 
end
cs


root 액션을 home 컨트롤러의 index 액션과 연결하도록 다음과 같이 수정합니다.

/root/blog/config/routes.rb

1
2
3
4
5
Rails.application.routes.draw do
  get 'home/index'
  root 'home#index'
 
end
cs


이제 http://localhost:3000 에 브라우저로 접속하면, Hello, Rails! 를 볼수 있습니다.


리소스 만들기


Scaffolding을 이용해 블로그에서 하나의 글을 표현하는 Post 리소스를 만듭니다.

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
32
33
34
35
36
37
root@localhost:~/blog# rails generate scaffold Post name:string title:string content:text
Running via Spring preloader in process 16954
      invoke  active_record
      create    db/migrate/20170717045752_create_posts.rb
      create    app/models/post.rb
      invoke    test_unit
      create      test/models/post_test.rb
      create      test/fixtures/posts.yml
      invoke  resource_route
       route    resources :posts
      invoke  scaffold_controller
      create    app/controllers/posts_controller.rb
      invoke    erb
      create      app/views/posts
      create      app/views/posts/index.html.erb
      create      app/views/posts/edit.html.erb
      create      app/views/posts/show.html.erb
      create      app/views/posts/new.html.erb
      create      app/views/posts/_form.html.erb
      invoke    test_unit
      create      test/controllers/posts_controller_test.rb
      invoke    helper
      create      app/helpers/posts_helper.rb
      invoke      test_unit
      invoke    jbuilder
      create      app/views/posts/index.json.jbuilder
      create      app/views/posts/show.json.jbuilder
      create      app/views/posts/_post.json.jbuilder
      invoke  test_unit
      create    test/system/posts_test.rb
      invoke  assets
      invoke    coffee
      create      app/assets/javascripts/posts.coffee
      invoke    scss
      create      app/assets/stylesheets/posts.scss
      invoke  scss
      create    app/assets/stylesheets/scaffolds.scss
cs


Scaffold 제너레이터는 어플리케이션내의 각 디렉토리에 다음과 같이 15개의 파일을 생성합니다.
 
파일 목적
db/migrate/20100207214725_create_posts.rb 데이터베이스에 ‘posts’ 테이블 생성하는 마이그레이션 (여러분의 파일 이름은, 다른 타임 스템프 값을 가지고 있습니다.)
app/models/post.rb Post 모델
test/fixtures/posts.yml 테스트를 위한 더미(Dummy) posts
app/controllers/posts_controller.rb Posts 컨트롤러
app/views/posts/index.html.erb 모든 posts 를 출력하는 index 뷰
app/views/posts/edit.html.erb 존재하는 post 를 수정하는 edit 뷰
app/views/posts/show.html.erb 단일 post를 보여주는 show 뷰
app/views/posts/new.html.erb 새로운 post 를 만들기 위한 new 뷰
app/views/posts/_form.html.erb post 를 수정하거나 새로 만드는데 사용되는 폼(form)을 저장하는 조각(partial) 파일
app/helpers/posts_helper.rb post 뷰를 위한 헬퍼(Helper) 함수를 위한 파일
test/unit/post_test.rb posts 모델을 위한 유닛 테스트 파일
test/functional/posts_controller_test.rb posts 컨트롤러를 위한 기능 테스트 파일
test/unit/helpers/posts_helper_test.rb posts 헬퍼(Helper)를 위한 유닛 테스트 파일
config/routes.rb posts 를 위한 라우팅 정보를 담은 수정된 라우팅 파일
public/stylesheets/scaffold.css 발판(Scaffold) 뷰를 좀 더 미려하게 만드는 CSS 파일


상기 명령으로 생성된 결과물 중 다음과 같이 데이터베이스 마이그레이션이 있습니다. 마이그레이션은 데이터베이스 테이블을 간단하게 생성하고 수정할 수 있도록 설계된 루비 클래스입니다.

/root/blog/db/migrate/20170717045752_create_posts.rb

1
2
3
4
5
6
7
8
9
10
11
class CreatePosts < ActiveRecord::Migration[5.1]
  def change
    create_table :posts do |t|
      t.string :name
      t.string :title
      t.text :content
 
      t.timestamps
    end
  end
end
cs


위의 마이그레이션 파일은 마이그레이션 작업을 수행하는 up과 나중에 적용된 마이그레이션을 되돌리는 down 이렇게 두가지의 메소드를 가집니다. 이 경우에 up 명령은 두개의 문자열(string) 컬럼과 하나의 텍스트(text) 컬럼을 가지는 posts 테이블을 생성합니다. 이 테이블은 생성(creation)과 업데이트(updating) 시점을 기록하는 두개의 타임스템프(timestamp) 컬럼도 가집니다.

이제 다음과 같이 rake 명령을 통해서 마이그레이션을 실행합니다.

1
2
3
4
5
root@localhost:~/blog# rake db:migrate
== 20170717045752 CreatePosts: migrating ======================================
-- create_table(:posts)
   -> 0.0034s
== 20170717045752 CreatePosts: migrated (0.0041s) =============================
cs


기본적으로 여러분은 개발(development) 환경에서 작업하기 때문에, 이 명령어는 config/database.yml 파일내의 development 부분에 있는 데이터베이스에 적용됩니다. 다른 환경, 예를 들면 제품(production) 환경에 적용하려면 다음과 같이 반드시 환경 변수 값을 명시적으로 넘겨주어야 합니다.

1
rake db:migrate RAILS_ENV=production
cs


생성된 홈페이지에 posts 쓰기를 추가하려면, 링크를 추가해야 합니다.  다음과 같이 수정합니다.

app/views/home/index.html.erb

1
<h1>Hello, Rails!</h1> <%= link_to "My Blog", posts_path %>
cs


link_to는 레일즈의 뷰 헬퍼로 내장된 메소드로, 이 메소드는 텍스트를 기반으로한 링크를 생성합니다. 이 경우에는 posts 의 경로입니다.

이제 posts 작업을 할 준비가 되었으므로, 이를 위해서 http://localhost:3000 로 이동한 후에 “My Blog” 링크를 클릭합니다.

posts를 위한 index 뷰를 볼 수 있습니다. New Post를 클릭하여 글을 만들 수 있습니다. 물론 수정, 내용조회, 삭제도 가능합니다. 이상의 모든 로직과 HTML은 단지 rails generate scaffold 명령어 한줄로 생성됩니다.





다음과 같이 진행이 되었습니다.

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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
root@localhost:~/blog# rails server
=> Booting Puma
=> Rails 5.1.2 application starting in development on http://localhost:3000
=> Run `rails server -h` for more startup options
Puma starting in single mode...
* Version 3.9.1 (ruby 2.4.1-p111), codename: Private Caller
* Min threads: 5, max threads: 5
* Environment: development
* Listening on tcp://0.0.0.0:3000
Use Ctrl-C to stop
Started GET "/" for ***.***.**.** at 2017-07-17 17:01:14 +0900
Cannot render console from ***.***.**.**! Allowed networks: 127.0.0.1, ::1127.0.0.0/127.255.255.255
   (0.3ms)  SELECT "schema_migrations"."version" FROM "schema_migrations" ORDER BY "schema_migrations"."version" ASC
Processing by HomeController#index as HTML
  Rendering home/index.html.erb within layouts/application
  Rendered home/index.html.erb within layouts/application (4.0ms)
Completed 200 OK in 633ms (Views: 607.2ms | ActiveRecord: 0.0ms)
 
 
Started GET "/posts" for ***.***.**.** at 2017-07-17 17:02:36 +0900
Cannot render console from ***.***.**.**! Allowed networks: 127.0.0.1, ::1127.0.0.0/127.255.255.255
Processing by PostsController#index as HTML
  Rendering posts/index.html.erb within layouts/application
  Post Load (0.3ms)  SELECT "posts".* FROM "posts"
  Rendered posts/index.html.erb within layouts/application (4.4ms)
Completed 200 OK in 40ms (Views: 32.3ms | ActiveRecord: 0.7ms)
 
 
Started GET "/posts/new" for ***.***.**.** at 2017-07-17 17:03:04 +0900
Cannot render console from ***.***.**.**! Allowed networks: 127.0.0.1, ::1127.0.0.0/127.255.255.255
Processing by PostsController#new as HTML
  Rendering posts/new.html.erb within layouts/application
  Rendered posts/_form.html.erb (175.9ms)
  Rendered posts/new.html.erb within layouts/application (177.7ms)
Completed 200 OK in 229ms (Views: 207.0ms | ActiveRecord: 0.6ms)
 
 
Started POST "/posts" for ***.***.**.** at 2017-07-17 17:04:02 +0900
Cannot render console from ***.***.**.**! Allowed networks: 127.0.0.1, ::1127.0.0.0/127.255.255.255
Processing by PostsController#create as HTML
  Parameters: {"utf8"=>"✓""authenticity_token"=>"**************************************""post"=>{"name"=>"관리자""title"=>"루비 온 레일즈 시작하기""content"=>"가이드를 따라서 해보자."}, "commit"=>"Create Post"}
   (0.2ms)  begin transaction
  SQL (4.1ms)  INSERT INTO "posts" ("name""title""content""created_at""updated_at") VALUES (?, ?, ?, ?, ?)  [["name""관리자"], ["title""루비 온 레일즈 시작하기"], ["content""가이드를 따라서 해보자."], ["created_at""2017-07-17 08:04:02.848333"], ["updated_at""2017-07-17 08:04:02.848333"]]
   (15.7ms)  commit transaction
Redirected to http://***.***.**.**:3000/posts/1
Completed 302 Found in 29ms (ActiveRecord: 20.0ms)
 
 
Started GET "/posts/1" for ***.***.**.** at 2017-07-17 17:04:02 +0900
Cannot render console from ***.***.**.**! Allowed networks: 127.0.0.1, ::1127.0.0.0/127.255.255.255
Processing by PostsController#show as HTML
  Parameters: {"id"=>"1"}
  Post Load (0.5ms)  SELECT  "posts".* FROM "posts" WHERE "posts"."id" = ? LIMIT ?  [["id"1], ["LIMIT"1]]
  Rendering posts/show.html.erb within layouts/application
  Rendered posts/show.html.erb within layouts/application (1.3ms)
Completed 200 OK in 136ms (Views: 31.9ms | ActiveRecord: 0.5ms)
 
 
Started GET "/posts" for ***.***.**.** at 2017-07-17 17:04:37 +0900
Cannot render console from ***.***.**.**! Allowed networks: 127.0.0.1, ::1127.0.0.0/127.255.255.255
Processing by PostsController#index as HTML
  Rendering posts/index.html.erb within layouts/application
  Post Load (0.5ms)  SELECT "posts".* FROM "posts"
  Rendered posts/index.html.erb within layouts/application (3.3ms)
Completed 200 OK in 50ms (Views: 48.6ms | ActiveRecord: 0.5ms)
 
 
 
 
cs