LoginSignup
0
0

More than 3 years have passed since last update.

最初に

カレンダー企画2020の19日目
プログラミングの勉強を始めて3ヵ月程経ったので学んだことのメモをアウトプットとして記事に残します。
これからプログラミングの世界に入る人の手助けになれたら嬉しい限りです。
間違っていたり、言葉が違っていたり、誤解されるような言葉があったら教えてください^^
言葉を長々と読みづらかったら申し訳ありません。少しずつなれてがんばります。

resourcesとresourceの違い

結論は
resources:indexとidが生成される
resource :indexとidが生成されない

resourcesメソッドとは?

railsの基本となる7つのアクション名に対してルーティングが自動生成されるメソッドです。

routes.rb
get  "posts/index" => "posts#index"
post "posts"       => "posts#create"

こんな感じでアクションごとにルーティングを設定します。
正直めんどくさいよね^^;

そんな時にresourcesメソッドの出番です。

routes.rb
resources :posts

この一行で7つのアクション名のルーティングが自動生成されます。
とても手間が省けて作業スピード上がります。

ターミナル
$ rails 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
          PATCH  /posts/:id(.:format)      posts#update
          PUT    /posts/:id(.:format)      posts#update
          DELETE /posts/:id(.:format)      posts#destroy

ルーティング確認する為にターミナルで確認するとこんな感じで出てくると思います。
ここで注目しておいてほしいのは、indexがあったり、/:idがありますね。

resourceメソッド

routes.rb
resource :posts

このようにして同様に出力してみると

ターミナル
$ rails routes

new_posts  GET    /posts/new(.:format)  posts#new
edit_posts GET    /posts/edit(.:format) posts#edit
     posts GET    /posts(.:format)      posts#show
           PATCH  /posts(.:format)      posts#update
           PUT    /posts(.:format)      posts#update
           DELETE /posts(.:format)      posts#destroy
           POST   /posts(.:format)      posts#create

こんな感じで出力されると思います。

indexと/:idが無くなっていますね。

最後に

こんな時に使いました

投稿機能にいいね機能をつける時に特別idが必要ないのでresourceを使いました。
userでid管理をしなくて良い時に使用した事もありました。

状況に応じて使い分けみるといいかもです。

個人的にID管理しない状態にしたい時、調べて知ったので書き残しておきます。

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