ActiveRecord RecordNotFound错误

时间:2015-10-09 23:05:09

标签: ruby-on-rails ruby-on-rails-4 activerecord

我使用脚手架创建了一个CRUD。

rails g scaffold intermediate_level/memory_game 

然后我创建了方法Play,但是当我调用方法播放时,会返回错误。 的 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])
    }

我的routes.file

namespace :intermediate_level do
    resources :memory_game
    get 'memory_game/play' 
  end

2 个答案:

答案 0 :(得分:1)

您的自定义get 'memory_game/play应该在resources :memory_game之前。 Rails按routes.rb文件中列出的顺序评估路由,最接近文件顶部的路由获得最高优先级。

答案 1 :(得分:1)

根据您提供的路线信息:

  namespace :intermediate_level do
    resources :memory_game
    get 'memory_game/play'
  end

您有以下两条路线:

GET    /intermediate_level/memory_game/:id(.:format)      intermediate_level/memory_game#show

GET    /intermediate_level/memory_game/play(.:format)     intermediate_level/memory_game#play

当您提出此请求时:

http://localhost:3000/intermediate_level/memory_game/play?id=1

它们与这两个路由相匹配,并且在您的resources :memory_game文件中定义了get 'memory_game/play' 之前的 routes.rb,所以第一个({{ 1}})因为具有更高的优先级而开始行动,(因为路由具有由GET /intermediate_level/memory_game/:id文件中的路由的出现顺序定义的优先级),然后它试图找到带有config/routes.rb param的记忆游戏,在这种情况下是id但未能这样做(因为你没有任何记忆游戏play)并且失败并显示错误消息:

id=play

解决此问题的一种快捷方法是重新排序您的路线,如下所示:

Couldn't find IntermediateLevel::MemoryGame with 'id'=play

然后,您的请求网址 namespace :intermediate_level do get 'memory_game/play' resources :memory_game end 将由http://localhost:3000/intermediate_level/memory_game/play?id=1路由提供,这是您想要的。