无法覆盖参数的URL编码

时间:2013-07-29 17:45:30

标签: ruby-on-rails ruby-on-rails-3 encoding

我有一个字符串,我想添加到一个URL变量,但我不能让Rails 编码它。

这就是我所拥有的:

<%= link_to "Example", example_path(@resource, email: '*|EMAIL|*') %>

输出是:

http://example.com/example/123?email=%2A%7CEMAIL%7C%2A

但我想:

http://example.com/example/123?email=*|EMAIL|*

我已尝试以下所有方法让*|EMAIL|*正确输出,但没有去...

<%= link_to "Example", example_path(@resource, email: '*|EMAIL|*').html_safe %>
<%= raw link_to "Example", example_path(@resource, email: '*|EMAIL|*') %>
<%= link_to "Example", example_path(@resource, email: '*|EMAIL|*'.html_safe) %>
<%= link_to "Example", example_path(@resource, email: raw('*|EMAIL|*')) %>

2 个答案:

答案 0 :(得分:1)

你可以试试像

这样的东西

<%= link_to "Example", example_path(@resource) + "?email=*|EMAIL|*" %>

也应该像

一样工作

<%= link_to "Example", example_path(@resource) + "?email=*|#{@instance_var.upcase}|*" %>如果这就是您要做的事情。

显然,按预期使用rails path helper会很好,但作为最后的手段,这应该可行。

您可能还需要对管道进行一些操作,请参阅:

How to prevent pipe character from causing a Bad URI Error in Rails 3/Ruby 1.9.2?

答案 1 :(得分:0)

我认为您的问题是实施link_to的方式

def link_to(*args, &block)
  ...
    url = url_for(options)

    href = html_options['href']
    tag_options = tag_options(html_options)

    href_attr = "href=\"#{ERB::Util.html_escape(url)}\"" unless href
    "<a #{href_attr}#{tag_options}>#{ERB::Util.html_escape(name || url)}</a>".html_safe
  end
end

在行href_attr = "href=\"#{ERB::Util.html_escape(url)}\"" unless href处,方法  ERB::Util.html_escape在其参数之前调用to_s,因此无论您对url使用什么,最终都会被转义。在href中设置html_options似乎是一种出路,但tag_options也会调用ERB::Util.html_escape

你可以做到

<a href="<%= example_path(@resource, email: '*|EMAIL|*'.html_safe) %>">Example</a>

我想。