如何在Rails 5的部分中传递URL作为参数?

时间:2016-11-09 16:36:27

标签: ruby-on-rails

我希望为我的应用程序中的多个对象的索引视图添加导出功能。索引视图看起来都一样,所以它们使用partials。 以下是Business Objects的index.html.erb:

<% provide(:title, (t('ManagingBOs')))  %>
<%= will_paginate %>
<%= render partial: "shared/simple_export", locals: {this_path: business_objects_path} %>
<%= render partial: "shared/object_index", locals: {this_index: @business_objects} %>
<%= will_paginate %>
<br />

我希望simple_export partial能够定义这样的导出链接,这可以很好地解决部分问题:

Download:
  <%= link_to "CSV", business_objects_path(format: "csv") %> |
  <%= link_to "Excel", business_objects_path(format: "xls") %>

不幸的是,语法<%= link_to "CSV", this_path(format: "csv") %>引发了未定义方法错误。

我如何实现这部分?

2 个答案:

答案 0 :(得分:1)

当你这样做时:

locals: {this_path: business_objects_path}

您没有传递方法business_objects_path。您正在调用方法business_objects_path并将结果字符串传递给partial。请记住,对于Ruby中的方法调用,parens是可选的。

如果要在Ruby中传递方法(函数引用),请使用method方法:

locals: {this_path: self.method(:business_objects_path) }

但是,你可以使用多态路由助手来代替查找方法。

<%= render partial: "shared/simple_export", resource_name: :business_objects %>
Download:
  <%= link_to "CSV", polymorphic_path(resource_name, format: "csv") %> |
  <%= link_to "Excel", polymorphic_path(resource_name, format: "xls") %>

答案 1 :(得分:0)

<%= link_to "CSV",   params.merge(:format => 'csv') %> |
<%= link_to "Excel", params.merge(:format => 'xls') %>

警告:此版本也可以使用,但可能存在潜在危险

select t.* from x,   
       xmltable('$X/test/xml'
          columns "type" int path 'data(@type)',
                  "text" varchar(10) path 'text()') as t

在视图中的任何位置都可以正常工作,而不必使用任何额外的变量。