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 5 years have passed since last update.

resourcesとresourceの使い方と違い

0
Last updated at Posted at 2020-02-29

ルーティング

Rails.application.routes.draw do
  [HTTPメソッド] '[URIパターン]', to: '[コントローラー名]#[アクション名]'
end

上記のようにHTTPメソッドを使うとアクションをひとつひとつ記述していかないといけないためコードが長くなり見にくかったりするためresourcesメソッドを使う

Rails.application.routes.draw do
  resources :リソース名
end

すると上記の記述だけですむ。resourcesメソッドは7つのアクションをまとめたものでテーブルに保存されるレコード1つの情報のことをリソースと呼ぶ

onlyオプション

指定したアクションだけに限定することができる。例えばindexとnewだけを指定したい場合は以下のように記載

Rails.application.routes.draw do
  root to: 'コントローラ名#アクション名'
  resources :リソース名, only: [:index, :new]
end

exceptオプション

指定したアクションを除外することができる。例えばshowだけを除外したい場合は以下のように記載

Rails.application.routes.draw do
  root to: 'コントローラ名#アクション名'
  resources :リソース名, except: :show
end

これで可読性が高くなる

resourcesとresourceの違い

resourcesは7つのアクション名に対してのルーティングを自動で生成してくれる。記述するときは複数形

resourceはidを必要としないときに使う。例えばサイトにログインした状態だとユーザーに紐付くidは絞り込む必要なくなる。そのためindexとid付きのパスが生成されない。記述するときは単数形
ちなみにターミナルにてrake routesを実行するとindexがないのが確認できます。

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?