LoginSignup
29
29

More than 5 years have passed since last update.

resourcesとresourceを組み合わせる際の注意点

Posted at
  • ユーザーの一覧は誰でも見れる
  • ユーザーの詳細は誰でも見れる
  • 自分のユーザー情報は編集できる

こんな仕様を実現するためのURL設計を考えます。
それぞれURLを以下のようにしようと思います。(自分の情報はmyを挟む流派もあるかも知れませんが知ったこっちゃありません)

  • GET /users
  • GET /users/:id
  • GET /users/edit
  • PUT /users

失敗

この時、以下のようにroutesを定義してみました。

config/routes.rb
resources :users, only: [:index, :show]
resource :users, only: [:edit, :update]

生成されたルートはこんなん。

rake routes
                  users GET    /users(.:format)                        users#index
                   user GET    /users/:id(.:format)                    users#show
             edit_users GET    /users/edit(.:format)                   users#edit
                        PUT    /users(.:format)                        users#update

うん。いいじゃん。
っんが、こんな感じでテストコケますよ、と。

Failures:
1) UsersController routing /users routing /users CRUD routes to #edit
Failure/Error: get("/#{resources}/edit").should route_to("#{resources}#edit")
The recognized options <{"action"=>"show", "controller"=>"users", "id"=>"edit"}> did not match <{"controller"=>"users", "action"=>"edit"}>, difference: <{"action"=>"edit", "id"=>"edit"}>.
<{"controller"=>"users", "action"=>"edit"}> expected but was
<{"action"=>"show", "controller"=>"users", "id"=>"edit"}>.

エラーメッセージにも書いてあるとおり、edit:idとして認識されちゃってますね。な、なるほどな。

というわけで、こういう場合はroutes定義の順番が大事さを実感するわけです。

成功

config/routes.rb
resource :users, only: [:edit, :update]
resources :users, only: [:index, :show]

順番変わっているかな?

rake routes
             edit_users GET    /users/edit(.:format)                   users#edit
                  users PUT    /users(.:format)                        users#update
                        GET    /users(.:format)                        users#index
                   user GET    /users/:id(.:format)                    users#show

よさげです。

29
29
3

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
29
29