路由存在的原因可以视为没有路由匹配(RoutingError)

Why does the route exist can be regarded as no route matches(RoutingError)?

本文关键字:路由 RoutingError 存在      更新时间:2023-09-26

rails服务器显示

Started POST "/user/1/follow" 
ActionController::RoutingError (No route matches [POST] "/user/1/follow"):

但是使用rake routes

         Prefix Verb   URI Pattern                     Controller#Action
 followers_user GET    /users/:id/followers(.:format)  users#followers
followings_user GET    /users/:id/followings(.:format) users#followings
    follow_user POST   /users/:id/follow(.:format)     users#follow

基于以上信息,我不知道为什么路由存在可以被视为没有路由匹配(RoutingError)。看来这条路线确实存在。

下面是可能与这个问题相关的其他信息。我使用jquery通过

触发路由
  $.ajax({
            url: '/user/'+userId+'/follow',
            type: 'POST',
        });

users#follow被定义为

    def follow
            if current_user?(@user)
                    flash[:error] = "You cannot follow yourself"
            elsif current_user.following?(@user)
                    flash[:error] = "You already follow #{@user.name}"
            end
            if request.xhr?
                    render status: current_user.follow(@user) ? 200 : 400, nothing: true
            end
    end

你已经将你的路由定义为

follow_user POST   /users/:id/follow(.:format)     users#follow

但是在jQuery代码片段中,你使用/user/...而不是/users/...

你的路由路径在jquery帖子中是不同的,正确的路由'users/1/follow',我在我的工作中使用的一个超级技巧,使用gem js-routes,它提供了在javascript中访问的路由路径。

希望这对你有帮助