【问题标题】:Rails app generating parameterized URLsRails 应用程序生成参数化 URL
【发布时间】:2012-03-12 12:57:42
【问题描述】:

我正在上 saas 课程,在做作业 2 时,rails 应用程序会生成参数化 URL,例如 http://localhost:3000/movies?sort=title

但是页面上的其他 URL 类似于 http://localhost:3000/movies/newhttp://localhost:3000/movies/1。我想知道为什么排序没有被解析为像 /movies/sort/title 这样的宁静 URL。

我们什么时候创建 RESTful URL 以及什么时候使用参数化 URL?

【问题讨论】:

    标签: ruby-on-rails restful-url


    【解决方案1】:

    REST(Rails 使用)对资源进行操作。具体来说,它使用 HTTP 动词(GET、POST、PUT、DELETE)对资源进行操作。

    假设您有一个电影模型。您可能有一个定义以下路线的电影资源:

    GET '/movies' - Gets a list of movies
    GET '/movies/new' - Gets the form to create a new movie
    POST '/movies' - Creates a new movie
    GET '/movies/:id' - Gets the details about the movie with :id
    GET '/movies/:id/edit' - Edits the movie with :id
    DELETE '/movies/:id' - Deletes the movie with :id
    PUT '/movies/:id' - Updates the movie with :id
    

    另一方面,排序是向 Rails 提供有关请求的附加信息的一种方式。因此,如果您要对模型或资源执行 CRUD 操作,您应该使用 RESTful 路由 (as described by the railsguide),否则您可能需要一个参数,或者您可以考虑使用 javascript 对数据客户端进行排序!

    请注意,没有什么可以阻止您实现类似 '/movies/sort/title' 的路由,它只是不是 RESTful 路由,需要在您的 routes.rb 文件中自定义路由。只需阅读我上面链接的 railsguide 即可了解完整的故事。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-04-27
      • 1970-01-01
      • 2017-06-16
      • 1970-01-01
      • 1970-01-01
      • 2023-03-20
      • 1970-01-01
      相关资源
      最近更新 更多