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 1 year has passed since last update.

shallowオプション

Posted at

##shallowオプションとは
ルーティングの記述を複雑にせず、かつ深いネストを作らないというバランスを保つことのできるオプションのこと。
簡単に言うと、rails routesした時のURLを短く分かりやすくしてくれるもの。

##shallowオプションの実例
###オプション無

resources :posts, only: %i(index show new create destroy) do
    resources :likes, only: %i(create destroy)
end

#URLを確認
$rails routes -c likes
    Prefix Verb   URI Pattern                         Controller#Action
post_likes POST   /posts/:post_id/likes(.:format)     likes#create
 post_like DELETE /posts/:post_id/likes/:id(.:format) likes#destroy

destroyアクションの/posts/:post_id/likes/:id(.:format)が見づらくなっている。これをshallowオプションで見やすくする。

###オプション有

resources :posts, only: %i(index show new create destroy) do
    resources :likes, only: %i(create destroy), shallow: true
  end

#URLを確認
$ rails routes -c likes
    Prefix Verb   URI Pattern                     Controller#Action
post_likes POST   /posts/:post_id/likes(.:format) likes#create
      like DELETE /likes/:id(.:format)            likes#destroy

destroyアクションの/posts/:post_id/likes/:id(.:format)/likes/:id(.:format) に短く変更され簡潔なURLになった。

今回は子リソースにshallowオプションをつけた例だったが、親リソースに直接shallowオプションを指定することもできる。

記述方法はとても簡単で、例にもあるようにshallow: trueを追加するだけである。

##参考記事
shallowオプションでroutesを整える

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?