如何使用slashes订单(/)获得有组织的搜索URL结果



我希望从books_controller的"索引"上进行搜索部分,并具有来自不同作者,类别和其他属性的一些过滤器选项。例如,我可以搜索一个类别的"浪漫"和最大页面=200。问题是我得到了这个(使用pg_search GEM)

http://localhost:3000/books?utf8 =%e2%9c%93& query%5btitle%5d = et et et et et et& button =

,但我想要这个:

http://localhost:3000/books/[category_name]/[rution]/[max_pages]/[other_options]

为了使我想从同一形式禁用" max_pages",我将获得此干净的URL:

http://localhost:3000/books/[category_name]/[作者]/[oter_options]

它将像我可以添加和删除的块一样工作。

我应该用什么方法来获得它?

obs:例如,本网站在URL上具有这种行为。

谢谢大家。

您可以为所需的格式和订单制定路由。路径参数包含在传递给控制器的params中,例如URL参数。

get "books/:category_name/:author/:max_pages/:other_options", to: "books#search"
class BooksController < ApplicationController
  def search
    params[:category_name] # etc.
  end
end

如果其他选项包括斜线,则可以使用Globbing。

get "books/:category_name/:author/:max_pages/*other"
"/books/history/farias/100/example/other"
params[:other]# "example/other"

使您获得基本形式,现在您显示的另一个形式可能只是另一个路径,因为参数计数更改了。

get "books/:category_name/:author/*other_options", to: "books#search"
params[:max_pages] # nil

如果您有多个具有相同数量的参数的路径,则可以添加约束将它们分开。

get "books/:category_name/:author/:max_pages/*other", constraints: {max_pages: /d+/}
get "books/:category_name/:author/*other"

《铁路指南》具有一些更详细的信息,来自"细分"对照"one_answers"高级约束":http://guides.rubyonrails.org/routing.html#sement segment-genter-constraints

如果您想到的格式不合理地适合所提供的路由,那么您也可以按照您的意愿将整个URL覆盖并解析。

get "books/*search"
search_components = params[:search].split "/"
#...decide what you want each component to mean to build a query

请记住,铁轨与第一个可能的路线匹配,因此您需要首先将更具体的路线(例如使用:max_pages和一个约束)放置在其他可能的路线(例如,使用:max_pages and a限制)(例如,匹配 *其他)。

<</p>

最新更新