LoginSignup
1
1

More than 5 years have passed since last update.

rails、君に決めた!!~3

Last updated at Posted at 2018-03-13

一連の記事の目次
rails、君に決めた!!~目次

前回の記事
rails君に決めた!!~2

アプリケーション開発

やっと開発編に入れる〜

ルーター

役割

ユーザーのリクエストをコントローラーのアクションと結びつける

これはあとで意味がじんわりわかる系なのでとりあえずこれだけで飛ばそう。

REST

REpresentational State Transferの略。

定義
* リソースは一意に特定できる
* ステートレスである
* URLはリソースの複数形で表す
* URLには動詞を含めず、HTTPメソッドで操作を指定する

うーん。。なんとなくしかわからない。

Railsではリソースはモデルとして表現する。

リソースは何かしらの機能を抽象的に理解したものなのかな。
ステートレスは「過去の注文を覚えてられない店員さん」って何かの本に書いてあった。

RESTに基づくルーティングの作成

実際にやってみよう!

bin/rails g scaffold user name:string email:string
bin/rails g scaffold article title:string contents:text

データベースのスキーマ定義をデータベースに反映
bin/rails db:migrate

scaffoldコマンドで、指定したリソース(user,articleなど)に対するモデル、ビュー、コントローラ、ルーティングの雛形を一度に生成できる。
ここら辺はDjangoより圧倒的に便利だなー。

scaffold: 足場

定義されたルーティングの確認

bin/rails routes

      Prefix Verb   URI Pattern                  Controller#Action
    articles GET    /articles(.:format)          articles#index
             POST   /articles(.:format)          articles#create
 new_article GET    /articles/new(.:format)      articles#new
edit_article GET    /articles/:id/edit(.:format) articles#edit
     article GET    /articles/:id(.:format)      articles#show
             PATCH  /articles/:id(.:format)      articles#update
             PUT    /articles/:id(.:format)      articles#update
             DELETE /articles/:id(.:format)      articles#destroy
       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
             PATCH  /users/:id(.:format)         users#update
             PUT    /users/:id(.:format)         users#update
             DELETE /users/:id(.:format)         users#destroy
  home_index GET    /home/index(.:format)        home#index

一行目を解釈してみる。
/articlesというURLにGETでアクセスすると、articles_controllerのindexアクションにルーティングされるよ、Prefix(Rails内で参照できる名前付きのルート)はarticlesだよ、となる。

Prefixが無いルートにもasオプションで名前をつけられる

だってさ、安心。

prefix: 接頭辞

1つのリソースに対して生成されたパスは8種類、重複してるupdateを除くと7種類のアクションが生成されている。URLは重複を除くと4種類生成されている。
7種のアクションを表でまとめてみる。

HTTPメソッド パス アクション 目的
GET /articles index articleの一覧を取得
POST /articles create articleを作成
GET /articles/new new articleを作成するためのformを取得
GET /articles/:id edit 特定のarticleを編集するためのformを取得
GET /articles/:id show 特定のarticleを一つ取得
PUT/PATCH /articles/:id update 特定のarticleを更新
DELETE /articles/:id delete 特定のarticleを削除

この表だけですごく勉強になる!fmfmという感じ笑
PUT :リソースそのものの更新
PATCH:リソースの部分置換

試しにサーバーを起動してhttp://localhost:3000/articles/newにアクセスしてみると
image.png
できとる!!
Djangoでここまで来るの結構大変だぞ...Railsすごい

config/routes.rb内にルーティングが定義されている。

Railsルーターの基本的なメソッド

  • resources
resources :articles
resources :articles, only: [:index, :show]

こんな感じで書くと、リソースに対するルーティングを生成してくれる。
:onlyとか:exceptを使うと、有効にするアクションを絞ることができる、、。
機能とURLをいい感じに対応させてくれるって程度の理解でいいのかな

  • resource

resourcesと違い、:idなどを持たないルーティングを生成。例えば、設定系のルーティングであれば、ログインしているユーザーidによって処理を分けるので、設定リソースのidは必要ない

ごめん、分からないww。ブログの記事とかだと1ユーザーに複数記事あるけど、設定画面とかは1ユーザー1つだから、設定idなくてもユーザーidあればいいよね?みたいな感じか??うん、きっとそうだと信じて進む。

  • get/post/patch/put/delete

ヘルプページなど、GETリクエストだけ受け付ければいいような、ほぼ静的なリソースを扱いたいとき使う

Rails.application.routes.draw do
  # ...
  get '/help', to: 'static_pages#help'
end

StaticPagesControllerのhelpアクションにルーティングされる。

ルーティングをもうちょっと細かく作ってみる

config/routes.rb

Rails.application.routes.draw do
  resources :articles
  resources :users
  get 'home/index'

  # 追加
  get '/hello', to: 'application#hello'
end

/helloというURLにGETリクエストでアクセスすると、ApplicationControllerのhelloアクションを呼び出す、というルーティングを追加した。

app/controllers/application_controller.rbにhelloアクションを実装

class ApplicationController < ActionController::Base
  protect_from_forgery with: :exception

  # 追加
  def hello
    text = 'Hello World!'
    render plain: text
  end
end

bin/rails sしてhttp://localhost:3000/helloにアクセスすると確認できた!

名前付きルート

Railsのアプリケーションから参照できる変数のようなルート名

get '/world', to: 'static_pages#world', as: 'foo'

のようにasを使ってエイリアスを作る。

名前付きルートを設定すると
名前付きルート_url
名前付きルート_path
という2つの名前付きヘルパーが使えるようになるらしい。

使ってみる。

$ bin/rails c
Loading development environment (Rails 5.1.5)
[1] pry(main)> app.new_article_path
=> "/articles/new"
[2] pry(main)> app.new_article_url
=> "http://www.example.com/articles/new"

~_url:絶対URL
~_path:相対パス

基本的にはpathを使った方がいいらしい。

パラメータの割り当て

URLの中に変数を埋め込む的な意味かな。
例えば

get 'users/@:user_name', to:'users#index', as:'user'

のように定義すると、

$ bin/rails c
Loading development environment (Rails 5.1.5)
[1] pry(main)> app.user_path(user_name: 'alice')
=> "/users/@alice"

変数名'alice'をURLに混ぜることができた。

今回は丸々ルータについてになっちゃったな
次回はコントローラー、セッション管理あたりをやろう

1
1
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
1
1