【问题标题】:How can overwrite the will_paginate urls? Will_paginate gem generate wrong url如何覆盖 will_paginate 网址? will_paginate gem 生成错误的 url
【发布时间】:2019-09-06 08:08:46
【问题描述】:

我有一个 ruby​​ on rails 应用程序,我使用 will_paginate 从类别中呈现我的产品。

我有 3 条路线可用于某些操作:

  • /category1
  • /category2
  • /category3

当我在 /category2 或 /category3 页面上时,will_paginate 会生成带有 /category1?page=nr_page 的 URL,而不是 /category1 url。

据我观察,如果我更改路由的顺序,will_paginate 将使用我的路由文件中的第一条路由生成 URL。

【问题讨论】:

  • 你能添加你的路由文件吗?看起来可能有问题。
  • 这是 mai route.rb 中的路线 get '/themes' => 'category#show_category',如: :all_themes get '/templates' => 'category#show_category',如: : all_templates 得到 '/design-system' => 'category#show_category',如::all_design_system
  • 您的show_category 操作看起来如何?
  • 我为 will_paginate 准备了这个:@products = @products.order("#{sort_column} #{sort_direction} #{free}").paginate(:page => (page || 1) , :per_page => 15)
  • 鉴于我有这个: "pagination pagination-azure pagination-no-border ".freeze, :previous_label => "«".freeze, :next_label => "»".freeze, :is_active => true %>

标签: ruby-on-rails ruby pagination routes will-paginate


【解决方案1】:

will_paginate 使用url_forparams 找出分页路径。根据您所说,您的路线文件如下所示:

get '/themes' => 'category#show_category', as: :all_themes 
get '/templates' => 'category#show_category', as: :all_templates 
get '/design-system' => 'category#show_category', as: :all_design_system

当您将 ` 添加到您的视图时。您会看到类似这样的内容(可能在哈希中包含更多参数):

<ActionController::Parameters {"controller"=>"category", "action"=>"show_category"} permitted: false>

这意味着将分页获取这些参数并在url_for 方法中使用它们。调用如下所示:

url_for controller: 'category', action: 'show_category', page: 123

它在浏览器中看不到当前路径,只有controlleraction 名称。在这种情况下,它从顶部遍历所有路由,直到找到给定控制器和操作的第一个定义规则,并从此规则中获取 url。这意味着它将始终使用列表中第一个定义的类别的 URL。

可能的解决方案

  1. 为每个类别定义不同的操作。如果您想以这种方式使用它,它会很好地为您服务
get '/themes' => 'category#themes', as: :all_themes 
get '/templates' => 'category#templates', as: :all_templates 
get '/design-system' => 'category#design_system', as: :all_design_system
  1. 用参数定义一个路由
get '/category/:category' => 'category#show_category', as: 'show_category'

然后在您的视图或控制器中使用以下链接:

  show_category_path(category: 'themes')

只是 URL 看起来不像以前那么好了。

【讨论】:

  • 感谢您的回复。这个解决方案对我不起作用,我需要这些路线用于 SEO 部分。我也有子类别,在 /category/subcategory 路径 will_paginate 工作得很好
  • 在这种情况下,请使用第一个建议的解决方案 - 为您拥有的每个类别创建自定义操作,不要为所有类别共享 show_category 操作。
  • 是的,建议的第一个应该可以。让我试试这个。
猜你喜欢
  • 2012-06-16
  • 1970-01-01
  • 1970-01-01
  • 2011-01-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-06-07
  • 2014-06-24
相关资源
最近更新 更多