0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

[Rails]ルーティング設定大全

Posted at

ルーティングの定義方法

通常の定義方法


get '/post/:id', to: 'posts#show'

resorces

リソースフルな一連のルーティングを生成する。(7つのアクション)


resources :posts
  • paramオプション

セグメント:idは、paramオプションで任意の値に変えることができる。


resources :posts, param: :no

# => /books/:no
  • only, exceptオプション

ルーティングを特定のアクションに限定したり、ルーティングから特定のアクションを除外したりすることができる。


resources :posts, only: [:show]

resources :posts, except: [:show]
  • collection、 memberオプション

collectionはidが必要ないルーティングに使用し、memberはidが必要なルーティングを使用する。


resources :posts, only:[] do
  collection do
    get :post_lndex , to: 'posts#post_index'
  end
  member do
    get :post_edit , to: 'posts#post_edit'
  end
end

resource

単数形リソース(id参照を必要としないリソース)を使用する時に使う。(indexアクション以外)


resource :user

root

アプリケーションルートのルーティングを生成する。


root 'welcome#index'

HttpHelpers

代表的なHTTPメソッドのヘルパーメソッドが定義されている。

  • match

matchではviaオプションを使って複数のHTTPメソッドに対応するルーティングを生成することができる。


match '/posts/:id', to: 'posts#update', as: 'post', via: [:put, :patch]

# => PUT|PATCH /posts/:id(.:format) posts#update
  • anchor

anchorオプションをfalseに設定すると、pathで始まるリソースに一致するリクエスト全てで有効となる。


match 'posts', to: 'posts#index', anchor: false, via: :get

scope

様々なスコープを作り、ルーティング設定を記述することができる。


scope '/posts' do
  get ':id', to: 'posts#show'
end

# => GET /books/:id(.:format) posts#show
  • controller

スコープ内でcontrollerオプションで指定されるcontrollerを使う。


scope '/posts', controller: :posts do
  get '/', to: :index
  post '/', to: :create
end

# =>  GET /posts(.:format) posts#index
# =>  POST /posts(.:format) posts#create
  • action

スコープ内でactionオプションで指定されるactionを使う。


scope '/posts/:id', controller: :posts, action: :update do
  match '/', via: [:put, :patch]
end

# => PUT|PATCH /posts/:id(.:format) posts#update
  • module

スコープ内でmoduleオプションで指定されるmoduleを使う。


scope '/admin', module: :admin, as: :admin do
  get '/', to: 'admin#index'
end

# => GET /admin(.:format) admin/admin#index
  • namespace

ルーティングの頭にnamespaceの名前が付く。


namespace :admin, as: 'admin' do
  # do something
end

参考

Railsのルーティングを理解する

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?