【问题标题】:How would I write a Rails route with a RESTful param in the middle of the URL?我如何在 URL 中间编写一个带有 RESTful 参数的 Rails 路由?
【发布时间】:2019-09-18 20:23:35
【问题描述】:

我正在使用 Rails 5。假设我想编写一个路由来支持以下形式的 URL

/posts/:key/comment

我希望它路由到我的 posts_controller 的“索引”操作。 ":key" 不是一个 ID,只是一个字母数字序列,我想在我的方法中使用 params[:key] 访问它。我的控制器中除了索引之外没有其他方法。我该怎么做?

【问题讨论】:

    标签: ruby-on-rails routes ruby-on-rails-5


    【解决方案1】:

    如果我这样做:

    get "posts/:key/comment", to: 'posts#index'
    resources :posts, only: [:index]
    

    ...然后我得到:

              GET    /posts/:key/comment(.:format)     posts#index
        posts GET    /posts(.:format)                  posts#index
    

    认为正是你要找的。​​p>

    【讨论】:

    • 肯定是的。有没有办法只拥有您列出的第一条路线(例如“GET /posts/:key/comment”)而没有其他路线?
    猜你喜欢
    • 1970-01-01
    • 2018-09-06
    • 2015-10-06
    • 1970-01-01
    • 2013-06-04
    • 2016-09-23
    • 1970-01-01
    • 2018-08-31
    • 1970-01-01
    相关资源
    最近更新 更多