【问题标题】:Unable to route to a method in my controller无法路由到我的控制器中的方法
【发布时间】:2016-07-03 23:39:51
【问题描述】:

我使用的是 Rails 4.2.5。我正在尝试设置我的控制器,以便当登录用户访问 /users/edit 时,他们可以看到我的表单,他们可以在其中编辑他们的一些配置文件。所以在 config/routes.rb 我有

  resources :users
  …
  get "users/edit" => "users#edit"

然后在“app/controllers/users_controller.rb”我有

  def edit
    @user = User.find(session["user_id"])
    render 'edit' 
  end

但是当我在浏览器中访问“http://localhost:3000/users/edit”时,我得到了错误

The action 'show' could not be found for UsersController

确实,我的控制器中没有“显示”方法,但这不是我希望用户去的地方。我希望他们去编辑方法。

【问题讨论】:

    标签: ruby-on-rails controller routes


    【解决方案1】:

    您正在尝试通过此链接进入表演活动:

    http://localhost:3000/users/edit
    

    你有这个显示动作的路线:

    GET /users/:id(.:format)    users#show
    

    (:id)(edit)

    因为你已经定义了第一个 RESTful 路由:

    resources :users 
    

    其中包括下列所有路线:

    users_path      GET       /users(.:format)           users#index
                    POST      /users(.:format)           users#create
    new_user_path   GET       /users/new(.:format)       users#new
    edit_user_path  GET       /users/:id/edit(.:format)  users#edit
    user_path       GET       /users/:id(.:format)       users#show
                    PATCH     /users/:id(.:format)       users#update
                    PUT       /users/:id(.:format)       users#update
                    DELETE    /users/:id(.:format)       users#destroy
    

    然后

    get "users/edit" => "users#edit"
    

    Rails 总是找到第一个匹配项。在这种情况下,将应用 RESTFul 路由的显示操作:

    GET /users/:id(.:format)    users#show
    

    而另一条路线将被忽略。

    解决方案:改变路线的顺序。这样编辑路线将首先应用。

    【讨论】:

      【解决方案2】:

      问题是您将资源路由与您自己的编辑方法和"Rails routes are matched in the order they are specified" 混合在一起,因此它与资源显示路由users/:id 匹配并停在那里。

      您需要将编辑路线移至资源上方。

      或者,阅读链接指南,看看是否可以将编辑添加为资源的集合路由,以及except 资源编辑方法。您可能还需要使用 show 方法,但值得一试并看看您的想法。路由是一个重要方面,值得花时间去理解。

      【讨论】:

      • K,我这样做了,但我得到了一个不同的错误,但我认为这与你的建议无关。在我解决另一个错误后,我会回来接受这个。谢谢,-
      【解决方案3】:

      从您的路由中删除 get "users/edit" => "users#edit",更改为 resources :users, only: [:edit](或更多,如果您需要它们的操作),从您的控制器中删除 render 'edit'(默认操作)。

      访问http://localhost:3000/users/1/edit查看user_id 1的编辑页面(不可能有所有用户的编辑页面,你必须指定id)

      【讨论】:

      • 我不想指定“localhost:3000/users/1/edit”,我想指定“localhost:3000/users/edit”并且我希望能够编辑当前登录用户的字段。跨度>
      • 然后你需要让它路由到当前用户 id 的编辑页面。在他们完成登录后,您可能有类似redirect_to edit_user_path 的信息,您需要给它一个用户ID(或只是整个用户对象)。所以redirect_to edit_user_path(@user)
      • @matt 路由应该是这样工作的......违反它就是违反 Rails 约定
      • @RoccoBasso Conventions != 限制,如果发布者想要为当前用户公开编辑方法而不公开他们的 id 为什么不应该这样做?设计 - 一个流行的身份验证宝石 - does exactly this!
      猜你喜欢
      • 2015-06-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多