如何将所有当前参数发送到路径?

问题描述 投票:1回答:2

我有一个可以选择导出到电子表格的表单,但是我需要电子表格与我页面中的报表具有相同的当前参数(过滤器)。像这样的东西:

  <a href="<%= reports_orders_path(params, format: 'xlsx') %>">
    <span><i class="fa fa-file-excel-o"></i></span>
    <%= t '.export_xlsx' %>
  </a>

我设法做到这样:

  <a href="<%= reports_orders_path(
    "by_event" => @event.id.to_s, 
    "by_document" => params[:by_document],
    "by_status" => params[:by_status],
    "by_method" => params[:by_method], 
    "by_date" => params[:by_date], 
    "by_period_init" => params[:by_period_init],
    "by_period_end" => params[:by_period_end],
    format: 'xlsx') %>">
    <span ><i class="fa fa-file-excel-o"></i></span>
    <%= t '.export_xlsx' %>
  </a>

但这感觉并且看起来很混乱。

是否有更好的方法来获取所有当前的params并将它们应用到我的路径?

ruby-on-rails ruby ruby-on-rails-4
2个回答
1
投票
# x_controller.rb
def action
  [...] #your code
  @filters = report_filters
end

def report_filters
  extract_fields = params.keys - ["_method", "authenticity_token", "commit", "controller", "action"] 

  { format: :xlsx, by_event: @event.id }.merge(params.slice(*extract_fields))
end

比如?

我绝对讨厌帮助者,因为随着时间的推移我不会发现它们是可维护的,并且根据我的经验容易产生巨大的技术债务。

编辑:动态参数提取


0
投票

清理标记的一种方法是将所需的参数提取到视图助手,如下所示:

# app/helpers/application_helper.rb

def filter_params
  {
    by_event: @event.id.to_s, 
    by_document: params[:by_document],
    by_status: params[:by_status],
    by_method: params[:by_method], 
    by_date: params[:by_date], 
    by_period_init: params[:by_period_init],
    by_period_end: params[:by_period_end],
    format: 'xlsx'
  }
end

然后在视图中,调用辅助方法来填充参数:

# app/views/your/view/path.html.erb

<%= link_to reports_orders_path(filter_params) do %>
  <span><i class="fa fa-file-excel-o"></i></span>
  <%= t '.export_xlsx' %>
<% end %>

希望这可以帮助!

© www.soinside.com 2019 - 2024. All rights reserved.