Reputation: 600
I created a CRUD using the scaffold .
rails g scaffold intermediate_level/memory_game
And then I created the method Play, but when I call the method play an error is returned. http://localhost:3000/intermediate_level/memory_game/play?id=1
Couldn't find IntermediateLevel::MemoryGame with 'id'=play
# Use callbacks to share common setup or constraints between actions.
def set_intermediate_level_memory_game
@intermediate_level_memory_game = IntermediateLevel::MemoryGame.find(params[:id])
end
def play {
@intermediate_level_memory_game = IntermediateLevel::MemoryGame.find(params[:id])
}
My routes.file
namespace :intermediate_level do
resources :memory_game
get 'memory_game/play'
end
Upvotes: 1
Views: 92
Reputation: 34336
With your given routes information:
namespace :intermediate_level do
resources :memory_game
get 'memory_game/play'
end
You have these two routes:
GET /intermediate_level/memory_game/:id(.:format) intermediate_level/memory_game#show
and
GET /intermediate_level/memory_game/play(.:format) intermediate_level/memory_game#play
When you make this request:
http://localhost:3000/intermediate_level/memory_game/play?id=1
it is matched by both of those routes and as you defined: resources :memory_game
before get 'memory_game/play'
in your routes.rb
file, so the first one (GET /intermediate_level/memory_game/:id
) comes into action as that has higher priority, (because Routes have priority defined by the order of appearance of the routes in the config/routes.rb
file) and then it tries to find the memory game with id
param which in that case is play
but fails to do so (as you don't have any memory game where id=play
) and fails with the error message:
Couldn't find IntermediateLevel::MemoryGame with 'id'=play
One quick way to get around this issue is to reorder your routes like this:
namespace :intermediate_level do
get 'memory_game/play'
resources :memory_game
end
Then, your request url http://localhost:3000/intermediate_level/memory_game/play?id=1
will be served by GET /intermediate_level/memory_game/play(.:format) intermediate_level/memory_game#play
route which is what you want.
Upvotes: 1
Reputation: 1854
Your custom get 'memory_game/play
should come before resources :memory_game
. Rails evaluates routes in the order in which they are listed in the routes.rb file, with the routes closest to the top of the file receiving the highest priority.
Upvotes: 1