LoginSignup
2
2

More than 5 years have passed since last update.

ドットインストールでRuby on Rails 3.2を学んだ際の詳細なメモ (9〜13)/全46

Last updated at Posted at 2014-03-09

主な内容

#09 ブログシステムを作ろう
#10 新しいプロジェクトを作ろう
#11 Postモデルを作ろう
#12 Postsコントローラーを作ろう
#13 ルーティングの設定をしよう

Scaffoldを使わずに、一からブログアプリケーションを作成しよう(実践的)
プロジェクト、Model、Controllerを作成し、ルーティングの設定をしよう

Blogシステムを作る

Scaffoldでは自動生成してくれたModel、DBの設定、Controller、URL、Controllerのメソッド、Viewを自力で作ります。

仕様

  1. Post(記事を投稿、編集、削除できる機能)
  2. Comment(記事に対してコメントを投稿、削除できる機能)

作成の流れ

  1. blogプロジェクトを作成
  2. Modelを作成
  3. DB
  4. Controllerの作成
  5. URLの作成(ルーティングの設定)
  6. Controllerのメソッドの作成
  7. メソッドに対応するViewを作成

1. blogプロジェクトを作成

railsprojectsへプロンプトを移動

Terminal
$ cd ..

blogプロジェクトを作成

Terminal
$ rails new blog
      create  
      create  README.rdoc
      create  Rakefile
      create  config.ru
      create  .gitignore
      create  Gemfile

〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜
        中略
〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜

Using rails 3.2.3
Using sass 3.3.0
Using sass-rails 3.2.6
Using sqlite3 1.3.9
Using uglifier 2.4.0
Your bundle is complete!
Use `bundle show [gemname]` to see where a bundled gem is installed.

blogプロジェクトへ移動

Terminal
$ cd blog

2. PostのModelを作成

PostのModelを作成する

railsコマンドで string型のタイトルとtext型の本文を持つ PostというModelを generateします。
modelの名前は必ず大文字から始めます。これはRailsの仕様なので、こうしなければなりません。
また、型は他にもintegerやbooleanなどたくさんあります。最後のまとめで示そうと思います。
ちなみに、
generateはgと短縮しても同じように動作します。便利ですね。

Terminal
$ rails generate model Post title:string content:text

↓同じ

Terminal
$ rails g model Post title:string content:text
Terminal
$ rails g model Post title:string content:text
        SECURITY WARNING: No secret option provided to Rack::Session::Cookie.
        This poses a security threat. It is strongly recommended that you
        provide a secret to prevent exploits that may be possible from crafted
        cookies. This will not be supported in future versions of Rack, and
        future versions will even invalidate your existing user cookies.

        Called from: /Users/shiraihiroki/.rbenv/versions/1.9.3-p125/lib/ruby/gems/1.9.1/gems/actionpack-3.2.3/lib/action_dispatch/middleware/session/abstract_store.rb:28:in `initialize'.

      invoke  active_record
      create    db/migrate/20140309021528_create_posts.rb
      create    app/models/post.rb
      invoke    test_unit
      create      test/unit/post_test.rb
      create      test/fixtures/posts.yml

SECURITY WARNINGが出ていますが、最新版のrubyを使っていないことが原因なので気にしないで進みます。

3. Modelを作成した際に生成されたmigrationファイルをデータベースに適応

Terminal
$ rake db:migrate
==  CreatePosts: migrating ====================================================
-- create_table(:posts)
   -> 0.0009s
==  CreatePosts: migrated (0.0010s) ===========================================

4. PostのControllerを作成

PostのControllerを作成

Controllerの名前は複数形で書きます。(例外がある)

Terminal
$ rails g controller Posts
        SECURITY WARNING: No secret option provided to Rack::Session::Cookie.
        This poses a security threat. It is strongly recommended that you
        provide a secret to prevent exploits that may be possible from crafted
        cookies. This will not be supported in future versions of Rack, and
        future versions will even invalidate your existing user cookies.

        Called from: /Users/shiraihiroki/.rbenv/versions/1.9.3-p125/lib/ruby/gems/1.9.1/gems/actionpack-3.2.3/lib/action_dispatch/middleware/session/abstract_store.rb:28:in `initialize'.

      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

5.ルーティングの設定

ルーティングの確認

rakeコマンドでルーティングURLを確認してみます。

Terminal
$ rake routes

ルーティングの設定を行う前はURLがなにもありません。

ルーティングの設定

ここで、config/routes.rbにpostsへのルーティング設定をします。
resources :postsを追記します。

resourcesはrailsで用意されているURL自動生成、設定機能です。HTTPメソッドとコントローラのアクションの対応付けを自動で行って、HTTPのメソッドを正しく使えるように(RESTfulという)生成、設定してくれます。
:オブジェクト名はシンボルと呼ばれるもので、一意性が担保されており、一度に全体を比較(検証)可能な文字列といったものです。文字列は一文字ずつ比較するので、シンボルの方が早くて良いということです。
ルーティングの設定は様々な方法があるので、一度リファレンスを読むと良いでしょう。

参考
RESTfulなURLを自動生成(resources)
Ruby のシンボル

config/routes.rb
Blog::Application.routes.draw do

  ## postsという一覧画面(index)、詳細画面(show)、
  #  登録画面(new)、登録処理(create)、編集画面(edit)、
  #  更新処理(update)、削除処理(destroy)へのURLを自動発行
  resources :posts

  # The priority is based upon order of creation:
  # first created -> highest priority.

  # Sample of regular route:
  #   match 'products/:id' => 'catalog#view'
  # Keep in mind you can assign values other than :controller and :action

〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜
         中略
〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜

  # Sample resource route within a namespace:
  #   namespace :admin do
  #     # Directs /admin/products/* to Admin::ProductsController
  #     # (app/controllers/admin/products_controller.rb)
  #     resources :products
  #   end

  # You can have the root of your site routed with "root"
  # just remember to delete public/index.html.
  # root :to => 'welcome#index'

  # See how all your routes lay out with "rake routes"

  # This is a legacy wild controller route that's not recommended for RESTful applications.
  # Note: This route will make all actions in every controller accessible via GET requests.
  # match ':controller(/:action(/:id))(.:format)'
end

ルーティングの再確認

config/routes.rbを上書き保存したら、もう一度ルーティングの確認をしてみます。新規作成機能、編集機能、削除機能などのURLが自動で設定されていることが確認できます。
一つ目は/postsにアクセスしたら、postsコントローラのindexメソッドを実行する
二つ目は/postsにクライアントからデータが渡されたら、postsコントローラのcreateメソッドを実行する
三つ目は/posts/newにアクセスしたら、postsコントローラのnewメソッドを実行する
・・・
と言った意味になります。

Terminal
$ 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

routes.rbについてもっと詳しく知りたいという人はココをみると良いでしょう。

次に続く。

メモ一覧

  1. ドットインストールでRuby on Rails 3.2を学んだ際の詳細なメモ (1〜2)/全46

    #01 Ruby on Railsとは何か?
    #02 必要となるツールを揃えよう

    • Ruby on Railsはこんなものですよ
    • 必要な情報はここら辺で集まりますよ
    • 必要な知識にはこんなものがありますよ
    • 開発環境はこんな感じですよ
  2. ドットインストールでRuby on Rails 3.2を学んだ際の詳細なメモ 3/全46

    #03 MVCとは何か?

    • Ruby on RailsはMVCフレームワークですよ
    • MVCはこんなものですよ
  3. ドットインストールでRuby on Rails 3.2を学んだ際の詳細なメモ (4〜8)/全46

    #04 はじめてのRailsプロジェクト
    #05 ファイル構成をみていこう
    アプリケーションを作成する基本的な流れを覚えましょう

    #06 Webサーバーを立ち上げよう
    作成したWebアプリケーションをどうささせてみましょう

    #07 scaffoldを使ってみよう (1)
    #08 scaffoldを使ってみよう (2)
    DB、Model、View、Controllerの作成、URLの設定をしてみましょう

  4. ドットインストールでRuby on Rails 3.2を学んだ際の詳細なメモ (9〜13)/全46

    #09 ブログシステムを作ろう
    #10 新しいプロジェクトを作ろう
    #11 Postモデルを作ろう
    #12 Postsコントローラーを作ろう
    #13 ルーティングの設定をしよう
    Scaffoldを使わずに、一からブログアプリケーションを作成しよう(実践的)
    プロジェクト、Model、Controllerを作成し、ルーティングの設定をしよう

  5. ドットインストールでRuby on Rails 3.2を学んだ際の詳細なメモ (14〜21)/全46

    #14 デバッグに使えるコンソールについて
    #15 コントローラーのメソッドについて
    #16 記事の一覧を表示する (1)
    #17 記事の一覧を表示する (2)
    #18 リンクを貼ってみよう
    #19 HTMLテンプレートを変更しよう
    #20 ロゴ画像を表示させてみよう
    #21 記事一覧画面をrootにしてみよう

    Scaffoldを使わずに、一からブログアプリケーションを作成しよう(実践的)(続き)
    rails consoleとか、rails dbconsoleなんかの便利なツールがありますよ
    コントローラーのメソッドと、それに対応するViewを作っていきましょう

    Scaffoldでは自動生成してくれたModel、DBの設定、Controller、URL、Controllerのメソッド、Viewを自力で作ります。(まずは1つ)

  6. ドットインストールでRuby on Rails 3.2を学んだ際の詳細なメモ (22〜23)/全46

    #22 記事の詳細を表示する (1)
    #23 記事の詳細を表示する (2)

    Scaffoldを使わずに、一からブログアプリケーションを作成しよう(実践的)(続き)

    • コントローラーのメソッドと、それに対応するViewを作っていきましょう(続き)
    • Scaffoldでは自動生成してくれたModel、DBの設定、Controller、URL、Controllerのメソッド、Viewを自力で作ります。(続き - show)
  7. ドットインストールでRuby on Rails 3.2を学んだ際の詳細なメモ (24〜30)/全46

    #24 新しい記事を追加しよう (1)
    #25 新しい記事を追加しよう (2)
    #26 新しい記事を追加しよう (3)
    #27 バリデーションを設定しよう
    #28 バリデーションエラーを表示しよう
    #29 フラッシュメッセージを表示する
    #30 メッセージをjQueryで消す

    Scaffoldを使わずに、一からブログアプリケーションを作成しよう(実践的)(続き)

    • コントローラーのメソッドと、それに対応するViewを作っていきましょう(続き)
    • Scaffoldでは自動生成してくれたModel、DBの設定、Controller、URL、Controllerのメソッド、Viewを自力で作ります。(続き - new,create)

    記事のタイトル一覧を表示するindexメソッド、その記事を表示するshowメソッドは完成したので次はその記事を表示するページが欲しいですね。ということでnewメソッド(新規作成フォーム)を作ります。また、フォームから送信されたデータを処理して新しい記事を作成するcreateメソッドも作成します。

    バリデーション(検査)の設定をやってみよう(実践的)

  8. ドットインストールでRuby on Rails 3.2を学んだ際の詳細なメモ (31〜33)/全46

    #31 記事を更新してみよう (1)
    #32 記事を更新してみよう (2)
    #33 記事を更新してみよう (3)
    Scaffoldを使わずに、一からブログアプリケーションを作成しよう(実践的)(続き)

    • コントローラーのメソッドと、それに対応するViewを作っていきましょう(続き)
    • Scaffoldでは自動生成してくれたModel、DBの設定、Controller、URL、Controllerのメソッド、Viewを自力で作ります。(続き - edit, update)

    記事のタイトル一覧を表示するindexメソッド、その記事を表示するshowメソッド、記事の新規作成フォームを作成するnewメソッド、記事を作成するcreateメソッドは完成したので次はその記事を編集するページが欲しいですね。ということでeditメソッド(記事編集フォーム)を作ります。また、フォームから送信されたデータを処理して記事を上書きするupdateメソッドも作成します。

  9. ドットインストールでRuby on Rails 3.2を学んだ際の詳細なメモ (34〜36)/全46

    #34 記事を削除してみよう
    #35 削除処理をAjax化しよう (1)
    #36 削除処理をAjax化しよう (2)
    Scaffoldを使わずに、一からブログアプリケーションを作成しよう(実践的)(続き)

    • コントローラーのメソッドと、それに対応するViewを作っていきましょう(続き)
    • Scaffoldでは自動生成してくれたModel、DBの設定、Controller、URL、Controllerのメソッド、Viewを自力で作ります。(続き - destroy)

    記事のタイトル一覧を表示するindex、その記事を表示するshow、記事の新規作成フォームを作成するnew、記事を作成するcreate、記事を編集するeditは完成したので次はその記事を削除するページが欲しいですね。ということでdestroyを作ります。

  10. ドットインストールでRuby on Rails 3.2を学んだ際の詳細なメモ (37〜46)/全46

    #37 Commentモデルを作ろう
    #38 Commentsコントローラーを作ろう
    #39 コメントを表示させよう
    #40 コメントを投稿してみよう (1)
    #41 コメントを投稿してみよう (2)
    #42 バリデーションを設定しよう
    #43 コメントを削除してみよう (1)
    #44 コメントを削除してみよう (2)
    #45 コメント件数を表示してみよう
    #46 Railsを日本語化しよう
    Scaffoldを使わずに、一からブログアプリケーションを作成しよう(実践的)(続き)

    • 新しい機能(Comment)を追加させましょう
    • Scaffoldでは自動生成してくれたModel、DBの設定、Controller、URL、Controllerのメソッド、Viewを自力で作ります。
2
2
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
2
2