LoginSignup
1
0

More than 1 year has passed since last update.

rails resourcesメソッドの使い方

Last updated at Posted at 2022-11-11

railsのresourcesメソッドを使う上で必要になった知識等を記録。

構文

config/routes.rb
Rails.application.routes.draw do
  namespace :api do
    resources :events, only: %i[index create]
  end
end

ルーティングをget user/index => user#indexみたいな感じじゃなくて、勝手にやってくれる。そのままだと全てのアクションにルーティングされるためonlyを使って使うアクションを限定する。

:idを別の名前に変更する

resourcesでshowなどをルーティングすると末尾が必ず:idというURLでリクエストを送ることになる。このこれを変えたいときは

config/routes.rb
Rails.application.routes.draw do
  namespace :api do
    resources :events, only: %i[show], param: :hashed_id
  end
end

と設定するとapi/events/:hashed_idって感じでルーティングしてくれる。

RESTful

HTTPリクエストを経由してフロントとバックエンドをしっかりと分けるときの設計思想。railsの開発は基本的にこの設計思想に基づいて行われているらしい。
この設計思想をルーティングに反映するためにちまちまget api/index => api#indexみたいに書くんじゃなくてresourcesを使うことで簡単に反映させることができる。

実際のルーティンを確認するコマンド

terminal
rails routes

これで実際にrailsで行われているルーティングが確認できる

参考

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