Ruby on Railsとは何か?

  • Webアプリケーションフレームワーク
  • 必要となる知識
    • Ruby
    • SQLite
    • Linux/vim
    • html/css/javascript/jQuery

必要となるツール

  • Ruby
  • RubyGem
  • Rails
  • SQLite(Macでは標準でプリインストール)
  • 各バージョン確認
$ ruby -v
ruby 1.8.7 (2012-02-08 patchlevel 358) [universal-darwin10.0]
$ rails -v
Rails 2.3.14
$ gem -v
1.3.5
$ sqlite3 -version
3.6.12

MVCとは何か?

  • Model:データに関するいろいろ
  • View:見た目に関するいろいろ
  • Controller:MとVをとりもつもの

はじめてのRailsプロジェクト

  1. railsコマンドでプロジェクトを作成
  2. Webサーバーを起動・ブラウザで確認
  3. DB/Model/View/Controller/URL
  4. 2に戻る
$ mkdir railsprojects
$ cd railsprojects/
$ rails new myapp
      create  
      create  app/controllers
      create  app/helpers
      create  app/models
      create  app/views/layouts
      create  config/environments
      create  config/initializers
      create  config/locales
      create  db
      create  doc
      create  lib
      create  lib/tasks
      create  log
      create  public/images
      create  public/javascripts
      create  public/stylesheets
      create  script/performance
      create  test/fixtures
      create  test/functional
      create  test/integration
      create  test/performance
      create  test/unit
      create  vendor
      create  vendor/plugins
      create  tmp/sessions
      create  tmp/sockets
      create  tmp/cache
      create  tmp/pids
      create  Rakefile
      create  README
      create  app/controllers/application_controller.rb
      create  app/helpers/application_helper.rb
      create  config/database.yml
      create  config/routes.rb
      create  config/locales/en.yml
      create  db/seeds.rb
      create  config/initializers/backtrace_silencers.rb
      create  config/initializers/inflections.rb
      create  config/initializers/mime_types.rb
      create  config/initializers/new_rails_defaults.rb
      create  config/initializers/session_store.rb
      create  config/initializers/cookie_verification_secret.rb
      create  config/environment.rb
      create  config/boot.rb
      create  config/environments/production.rb
      create  config/environments/development.rb
      create  config/environments/test.rb
      create  script/about
      create  script/console
      create  script/dbconsole
      create  script/destroy
      create  script/generate
      create  script/runner
      create  script/server
      create  script/plugin
      create  script/performance/benchmarker
      create  script/performance/profiler
      create  test/test_helper.rb
      create  test/performance/browsing_test.rb
      create  public/404.html
      create  public/422.html
      create  public/500.html
      create  public/index.html
      create  public/favicon.ico
      create  public/robots.txt
      create  public/images/rails.png
      create  public/javascripts/prototype.js
      create  public/javascripts/effects.js
      create  public/javascripts/dragdrop.js
      create  public/javascripts/controls.js
      create  public/javascripts/application.js
      create  doc/README_FOR_APP
      create  log/server.log
      create  log/production.log
      create  log/development.log
      create  log/test.log

ファイル構成をみていこう

  • appフォルダ:Model, View, Controller
  • config:設定ファイル
  • db:データベースに関するもの
  • Gemfile:必要なライブラリ一覧

Webサーバーを立ち上げよう

  • WEBrick(標準の開発用サーバー)の起動
$ cd myapp/
$ rails server
=> Booting WEBrick
=> Rails 3.2.9 application starting in development on http://0.0.0.0:3000
=> Call with -d to detach
=> Ctrl-C to shutdown server
[2012-12-29 19:11:47] INFO  WEBrick 1.3.1
[2012-12-29 19:11:47] INFO  ruby 1.9.2 (2012-04-20) [x86_64-darwin10.8.0]
[2012-12-29 19:11:47] INFO  WEBrick::HTTPServer#start: pid=22257 port=3000
  • Rails 2.3.14の場合 ※ rails serverコマンド利用不可(MacOS 10.6.8 / ruby 1.8.7 / Rails 2.3.14)
$ ruby script/server webrick
=> Booting WEBrick
=> Rails 2.3.14 application starting on http://0.0.0.0:3000
=> Call with -d to detach
=> Ctrl-C to shutdown server
[2012-12-29 16:19:53] INFO  WEBrick 1.3.1
[2012-12-29 16:19:53] INFO  ruby 1.8.7 (2012-02-08) [universal-darwin10.0]
[2012-12-29 16:19:54] INFO  WEBrick::HTTPServer#start: pid=412 port=3000
  • ブラウザでの確認(ポート番号を3000に指定)
http://localhost:3000

scaffoldを使ってみよう

  • scaffold:簡易的にDB/Model/View/Controller/URLを設計・生成
$ rails generate scaffold User name:string email:string intro:text
      invoke  active_record
      create    db/migrate/20130101040551_create_users.rb
      create    app/models/user.rb
      invoke    test_unit
      create      test/unit/user_test.rb
      create      test/fixtures/users.yml
      invoke  resource_route
       route    resources :users
      invoke  scaffold_controller
      create    app/controllers/users_controller.rb
      invoke    erb
      create      app/views/users
      create      app/views/users/index.html.erb
      create      app/views/users/edit.html.erb
      create      app/views/users/show.html.erb
      create      app/views/users/new.html.erb
      create      app/views/users/_form.html.erb
      invoke    test_unit
      create      test/functional/users_controller_test.rb
      invoke    helper
      create      app/helpers/users_helper.rb
      invoke      test_unit
      create        test/unit/helpers/users_helper_test.rb
      invoke  assets
      invoke    coffee
      create      app/assets/javascripts/users.js.coffee
      invoke    scss
      create      app/assets/stylesheets/users.css.scss
      invoke  scss
      create    app/assets/stylesheets/scaffolds.css.scss
  • myapp > app > controllers, models, viewsにユーザファイルが作成
  • myapp > db > DBファイルとmigration(DBを設定する)ファイルが生成
  • migrationファイルをDBに反映(下記コマンドでテーブル作成)
$ rake db:migrate
==  CreateUsers: migrating ====================================================
-- create_table(:users)
   -> 0.0029s
==  CreateUsers: migrated (0.0042s) ===========================================
  • 有効なルーティング(URL)一覧を表示
$ rake routes
    users GET    /users(.:format)          users#index
          POST   /users(.:format)          users#create
 new_user GET    /users/new(.:format)      users#new
edit_user GET    /users/:id/edit(.:format) users#edit
     user GET    /users/:id(.:format)      users#show
          PUT    /users/:id(.:format)      users#update
          DELETE /users/:id(.:format)      users#destroy
  • サーバー起動
$ rails server
  • ブラウザで確認(下記URLが有効)
http://localhost:3000/users
  • Name, Email, Introにデータを入力・編集・削除可能になっていることを確認

ブログシステムを作ろう

  1. Projectを作る(rails new ...)
  2. Post(Model/DB/Controller/URL/View)
  3. Comment(Model/DB/URL/Controller/View)

Projectを作る

  • 「blog」プロジェクトを作成(--skip-bundleオプションは新規でgemをインストール不要の意味)
$ rails new blog --skip-bundle
  • JavaScript Runtimeの導入
$ cd blog
$ vim Gemfile # 下記をアンコメント
gem 'therubyracer', :platforms => :ruby
$ bundle install # therubyracerのインストール
  • therubyracerのインストール段階で下記エラー発生
$ bundle install
Fetching gem metadata from https://rubygems.org/...........
Fetching gem metadata from https://rubygems.org/..
Using rake (10.0.3) 
Using i18n (0.6.1) 
Using multi_json (1.5.0) 
Using activesupport (3.2.9) 
Using builder (3.0.4) 
Using activemodel (3.2.9) 
Using erubis (2.7.0) 
Using journey (1.0.4) 
Using rack (1.4.1) 
Using rack-cache (1.2) 
Using rack-test (0.6.2) 
Using hike (1.2.1) 
Using tilt (1.3.3) 
Using sprockets (2.2.2) 
Using actionpack (3.2.9) 
Using mime-types (1.19) 
Using polyglot (0.3.3) 
Using treetop (1.4.12) 
Using mail (2.4.4) 
Using actionmailer (3.2.9) 
Using arel (3.0.2) 
Using tzinfo (0.3.35) 
Using activerecord (3.2.9) 
Using activeresource (3.2.9) 
Using bundler (1.2.3) 
Using coffee-script-source (1.4.0) 
Using execjs (1.4.0) 
Using coffee-script (2.2.0) 
Using rack-ssl (1.3.2) 
Using json (1.7.6) 
Using rdoc (3.12) 
Using thor (0.16.0) 
Using railties (3.2.9) 
Using coffee-rails (3.2.2) 
Using jquery-rails (2.1.4) 
Using rails (3.2.9) 
Using ref (1.0.2) 
Using sass (3.2.4) 
Using sass-rails (3.2.5) 
Using sqlite3 (1.3.6) 
Installing therubyracer (0.11.0) with native extensions 
Gem::Installer::ExtensionBuildError: ERROR: Failed to build gem native extension.

       /Users/yujishimojo/.rvm/rubies/ruby-1.9.2-p320/bin/ruby extconf.rb 
checking for main() in -lpthread... yes
checking for main() in -lobjc... yes
checking for v8.h... no
*** extconf.rb failed ***
Could not create Makefile due to some reason, probably lack of
necessary libraries and/or headers.  Check the mkmf.log file for more
details.  You may need configuration options.

Provided configuration options:
       --with-opt-dir
       --without-opt-dir
       --with-opt-include
       --without-opt-include=${opt-dir}/include
       --with-opt-lib
       --without-opt-lib=${opt-dir}/lib
       --with-make-prog
       --without-make-prog
       --srcdir=.
       --curdir
       --ruby=/Users/yujishimojo/.rvm/rubies/ruby-1.9.2-p320/bin/ruby
       --with-pthreadlib
       --without-pthreadlib
       --with-objclib
       --without-objclib
       --enable-debug
       --disable-debug
       --with-v8-dir
       --without-v8-dir
       --with-v8-include
       --without-v8-include=${v8-dir}/include
       --with-v8-lib
       --without-v8-lib=${v8-dir}/lib
/Users/yujishimojo/.rvm/gems/ruby-1.9.2-p320/gems/therubyracer-0.11.0/ext/v8/build.rb:42:in `build_with_system_libv8': unable to locate libv8. Please see output for details (RuntimeError)
       from extconf.rb:22:in `<main>'
    The Ruby Racer requires libv8 ~> 3.11.8
    to be present on your system in order to compile
    and link, but it could not be found.

    In order to resolve this, you will either need to manually
    install an appropriate libv8 and make sure that this
    build process can find it. If you install it into the
    standard system path, then it should just be picked up
    automatically. Otherwise, you'll have to pass some extra
    flags to the build process as a hint.

    If you don't want to bother with all that, there is a
    rubygem that will do all this for you. You can add
    following line to your Gemfile:
        gem 'libv8', '~> 3.11.8'

    We hope that helps, and we apologize, but now we have
    to push the eject button on this install.

    thanks,
    The Mgmt.



Gem files will remain installed in /Users/yujishimojo/.rvm/gems/ruby-1.9.2-p320/gems/therubyracer-0.11.0 for inspection.
Results logged to /Users/yujishimojo/.rvm/gems/ruby-1.9.2-p320/gems/therubyracer-0.11.0/ext/v8/gem_make.out
An error occurred while installing therubyracer (0.11.0), and Bundler cannot continue.
Make sure that `gem install therubyracer -v '0.11.0'` succeeds before bundling.
  • libv8が無いことが原因のため同ファイルをインストール
$ gem install libv8
Fetching: libv8-3.11.8.4.gem (100%)
Building native extensions.  This could take a while...

Successfully installed libv8-3.11.8.4
1 gem installed
Installing ri documentation for libv8-3.11.8.4...
Installing RDoc documentation for libv8-3.11.8.4...
  • libv8がインストールされていることを確認
$ gem list --local

*** LOCAL GEMS ***

actionmailer (3.2.9)
actionpack (3.2.9)
activemodel (3.2.9)
activerecord (3.2.9)
activeresource (3.2.9)
activesupport (3.2.9)
arel (3.0.2)
builder (3.1.4, 3.0.4)
bundler (1.2.3)
coffee-rails (3.2.2)
coffee-script (2.2.0)
coffee-script-source (1.4.0)
erubis (2.7.0)
execjs (1.4.0)
hike (1.2.1)
i18n (0.6.1)
journey (1.0.4)
jquery-rails (2.1.4)
json (1.7.6, 1.7.5)
libv8 (3.11.8.4)
mail (2.5.3, 2.4.4)
mime-types (1.19)
multi_json (1.5.0)
polyglot (0.3.3)
rack (1.4.1)
rack-cache (1.2)
rack-ssl (1.3.2)
rack-test (0.6.2)
rails (3.2.9)
railties (3.2.9)
rake (10.0.3)
rdoc (3.12)
ref (1.0.2)
rubygems-bundler (1.1.0)
rvm (1.11.3.5)
sass (3.2.4)
sass-rails (3.2.5)
sprockets (2.8.2, 2.2.2)
sqlite3 (1.3.6)
thor (0.16.0)
tilt (1.3.3)
treetop (1.4.12)
tzinfo (0.3.35)
uglifier (1.3.0)
  • 再度bundle installを実行しインストール成功
$ bundle install
Fetching gem metadata from https://rubygems.org/...........

...
... 

Installing therubyracer (0.11.0) with native extensions 
Using uglifier (1.3.0) 
Your bundle is complete! Use `bundle show [gemname]` to see where a bundled gem is installed.
  • データベースの初期化
$ rake db:create

Postモデルを作ろう

  • モデルを作成(rails g = rails generateでも可)
$ rails g model Post title:string content:text
      invoke  active_record
      create    db/migrate/20130101080138_create_posts.rb
      create    app/models/post.rb
      invoke    test_unit
      create      test/unit/post_test.rb
      create      test/fixtures/posts.yml
$ rake db:migrate

Postsコントローラーを作ろう

  • コントローラーを作成
$ rails g controller Posts
      create  app/controllers/posts_controller.rb
      invoke  erb
      create    app/views/posts
      invoke  test_unit
      create    test/functional/posts_controller_test.rb
      invoke  helper
      create    app/helpers/posts_helper.rb
      invoke    test_unit
      create      test/unit/helpers/posts_helper_test.rb
      invoke  assets
      invoke    coffee
      create      app/assets/javascripts/posts.js.coffee
      invoke    scss
      create      app/assets/stylesheets/posts.css.scss

ルーティングの設定をしよう

  • config/routes.rbを編集(下記を追加)
resources :posts
  • routes.rbで定義したルーティングを表示
$ rake routes
    posts GET    /posts(.:format)          posts#index
          POST   /posts(.:format)          posts#create
 new_post GET    /posts/new(.:format)      posts#new
edit_post GET    /posts/:id/edit(.:format) posts#edit
     post GET    /posts/:id(.:format)      posts#show
          PUT    /posts/:id(.:format)      posts#update
          DELETE /posts/:id(.:format)      posts#destroy
  • 上記「posts#index」は当該URLに対して「postsコントローラー」の「index」メソッド(アクション)を実行するという意味

トップ   編集 凍結 差分 バックアップ 添付 複製 名前変更 リロード   新規 一覧 単語検索 最終更新   ヘルプ   最終更新のRSS
Last-modified: 2013-08-10 (土) 01:53:05 (3906d)