(GoRails)链接link_to到当前页current Page 并使用参数 (类ActionController::Parameters)


https://gorails.com/episodes/rails-link-to-current-page-with-params?autoplay=1

如何链接到当前页并增加,移除,或者修改URL中的params。

当使用search or index pages with filters很方便。

  <%= link_to "Customers", root_path %>

  <%= link_to "Paid Customers", root_path(paid: true) %>

  #对URL中的参数进行筛选 <%= link_to "Customers Date Range", request.params.except(:end) %> <%= link_to "Paid Customers Date Range", current_page_params.merge(paid: true) %>

假如:http://localhost:3000/?start=1990&end=2020

通过except方法,最后只会得到 Parameters: { "start" =>  1990 }

merge方法,是把paid参数加入到URL中。

这些方法都是ActionController::Parameters类中的方法

把request.params定义成一个helper方法:

#app/helpers/xxx_helper.rb
module HomeHelper
  def current_page_params
    request.params.slice("paid", "query", "filter", "sort")
  end
end

#slice是参数白名单
原文地址:https://www.cnblogs.com/chentianwei/p/9940601.html