Rails 3 路由中的负正则表达式约束

发布于 2024-11-14 06:08:36 字数 931 浏览 2 评论 0原文

我有一些租赁列表,我希望可以作为 RESTful 资源进行访问,但也可以通过 :area 参数(可以是社区或区域)过滤索引。考虑到“租赁”资源,我希望

/rentals

在根级别拥有 :area 参数过滤,

/downtown
/westside
/some-neighborhood
etc.

我想我可以通过将以下内容放在我的路线文件底部附近来使其工作:

resources :rentals
get ':area' => 'rentals#index', :area => /[a-zA-Z0-9\-]+/, :as => :area

但是当我添加 Kaminari 时对于分页,它会自动生成分页链接,看起来像

/rentals?area=downtown&page=2

我希望它看起来像的

/downtown?page=2

样子为了让 Kaminari 使用命名路由版本,:area 参数需要具有优先级,所以我更改了路由到:

get ':area' => 'rentals#index', :area => /(?!rentals)[a-zA-Z0-9\-]+/, :as => :area
resources :rentals

但是当我尝试识别控制台中的路线时,我得到:

ActionController::RoutingError: No route matches {:controller=>"rentals", :area=>"downtown"}

我不知道如何解决这个问题,所以任何帮助将不胜感激。

I have some rental listings that I want to be accessible as RESTful resource, but also have the index be filtered through an :area parameter, which could be a neighborhood or region. Given the 'rentals' resource, I'd like to have

/rentals

as well as the :area param filtering at the root level

/downtown
/westside
/some-neighborhood
etc.

I thought I could get this to work by putting the following near the bottom of my routes file:

resources :rentals
get ':area' => 'rentals#index', :area => /[a-zA-Z0-9\-]+/, :as => :area

But when I added Kaminari for pagination, it would auto-generate the pagination links to look something like

/rentals?area=downtown&page=2

when I'd rather have it look like

/downtown?page=2

In order to get Kaminari to use the named route version, the :area param needs to have priority, so I changed the routes to:

get ':area' => 'rentals#index', :area => /(?!rentals)[a-zA-Z0-9\-]+/, :as => :area
resources :rentals

But when I try to recognize the route in the console, I get:

ActionController::RoutingError: No route matches {:controller=>"rentals", :area=>"downtown"}

I'm not sure how to approach solving this, so any help would be appreciated.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

短叹 2024-11-21 06:08:36

您可以在路由约束中使用 lambda 来解决此问题

match ':area' => 'rentals#index', :constraints => lambda{|req|  !req.env["REQUEST_URI"].include? "rentals"}

You can use lambdas in your route constraints to solve this problem

match ':area' => 'rentals#index', :constraints => lambda{|req|  !req.env["REQUEST_URI"].include? "rentals"}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文