LoginSignup
1
1

routesの`:id`の部分をid以外にしたい備忘録

Posted at

resources :furnituresとした時に生成されるURLは↓こんな感じになると思います。

furnitures#index GET /furnitures
furnitures#create POST /furnitures
furnitures#new GET /furnitures/:id/edit
furnitures#edit GET /furnitures/:id
furnitures#show GET /furnitures/:id
furnitures#update PUT /furnitures/:id
furnitures#destroy DELETE /furnitures/:id

show画面だと/furnitures/1とかになると思うのですが、この数字(:id)を変えて、/furnitures/sofa /furnitures/tableという感じにしたい。
公式ドキュメント


resourcesにparamオプションをつければ可能になる。

# 例えばslugカラムがあったとしたら
resources :furnitures, param: :slug

コントローラーには普段:idを渡すところを:slugにすればOK

def show
   @furniture = Furniture.find_by(slug: params[:slug])
end

URLはちゃんとそれっぽくなる

furnitures#index GET /furnitures
furnitures#new GET /furnitures/:slug/edit
furnitures#edit GET /furnitures/:slug
furnitures#show GET /furnitures/:slug
furnitures#update PUT /furnitures/:slug
furnitures#destroy DELETE /furnitures/:slug
1
1
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
1