ruby-on-rails – Rails路由错误? “没有路线匹配”

前端之家收集整理的这篇文章主要介绍了ruby-on-rails – Rails路由错误? “没有路线匹配”前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
所以我不断遇到以下错误

No route matches {:action=>"show",:controller=>"users"}

我尝试运行耙子路线,我可以看到路线存在:

  1. user GET /users/:id(.:format) users#show
  2. PUT /users/:id(.:format) users#update
  3. DELETE /users/:id(.:format) users#destroy

但是每次尝试访问页面“/ users / 1”(1是用户ID)时,我得到上面的错误.有任何想法吗?谢谢!

这是我的routes.rb:

  1. SampleApp::Application.routes.draw do
  2. root to: 'static_pages#home'
  3.  
  4. resources :users
  5. resource :sessions,only: [:new,:create,:destroy]
  6.  
  7.  
  8. match '/signup',to: 'users#new'
  9. match '/signin',to: 'sessions#new'
  10. match '/signout',to: 'sessions#destroy',via: :delete
  11.  
  12. match '/help',to: 'static_pages#help'
  13. match '/about',to: 'static_pages#about'
  14. match '/contact',to: 'static_pages#contact'

这是我的users_controller.rb:

  1. class UsersController < ApplicationController
  2.  
  3. before_filter :signed_in_user,only: [:index,:edit,:update]
  4. before_filter :correct_user,only: [:edit,:update]
  5.  
  6. def show
  7. @user = User.find(params[:id])
  8. end
  9.  
  10. def new
  11. @user = User.new
  12. end
  13.  
  14. def create
  15. @user = User.new(params[:user])
  16. if @user.save
  17. sign_in @user
  18. flash[:success] = "Welcome to the Paper Piazza!"
  19. redirect_to @user
  20. else
  21. render 'new'
  22. end
  23. end
  24.  
  25. def edit
  26. @user = User.find(params[:id])
  27. end
  28.  
  29. def update
  30. if @user.update_attributes(params[:user])
  31. flash[:success] = "Profile updated"
  32. sign_in @user
  33. redirect_to @user
  34. else
  35. render 'edit'
  36. end
  37. end
  38.  
  39. def index
  40. @users = User.paginate(page: params[:page])
  41. end
  42.  
  43. private
  44.  
  45. def signed_in_user
  46. unless signed_in?
  47. store_location
  48. redirect_to signin_path,notice: "Please sign in."
  49. end
  50. end
  51.  
  52. def correct_user
  53. @user = User.find(params[:id])
  54. redirect_to(root_path) unless current_user?(@user)
  55. end
  56. end

解决方法

尝试修复打字错误
  1. root :to 'static_pages#home'

(而不是根到:),并将其移动到块的最后一行.让我知道这是否有所作为!

很奇怪的是,我用一个路由文件创建了一个新的项目,只需读取:

  1. RoutingTest::Application.routes.draw do
  2. resources :users
  3. root :to => "static_pages#home"
  4. end

当我在控制台中运行这个操作时,我遇到了同样的错误

  1. >> r = Rails.application.routes ; true
  2. => true
  3. >> r.recognize_path("/users/1")
  4. => ActionController::RoutingError: No route matches "/users"

…但是当我在一个稍旧的项目中运行相同的事情时,我得到:

  1. >> r = Rails.application.routes ; true
  2. => true
  3. >> r.recognize_path("/users/1")
  4. => {:action=>"show",:controller=>"users",:id=>"1"}

所以我几乎没有信心我所告诉你会有所作为. (除此之外,Rails.application.routes技巧对于验证控制台中的路径非常有用!)

猜你在找的Ruby相关文章