简体   繁体   English

使用Rails中的GET参数为外部站点创建URL

[英]Create URL for external site with GET parameters in Rails

I'm making a Tweet This link in Rails. 我在Rails中发了一条推文。 The URL I need to generate looks something like this: 我需要生成的URL看起来像这样:

http://twitter.com/share?url=http%3A%2F%2Fexample.com&text=Hello%20World

but a bit more complex. 但有点复杂。 Basically a URL with a load of GET parameters appended 基本上是一个附加了GET参数加载的URL

It would be nice to use one of Rails' helpers, to generate this link, something like: 使用Rails的助手之一来生成这个链接会很不错,例如:

url_for("http://twitter.com/share", :url => "http://example.com", :text => "Hello world")

But I haven't found anything that works. 但我没有发现任何有效的东西。 Anyone have any ideas? 有人有想法么?

You can call to_query on Hash in rails which will take care of url encoding etc. So maybe something like this: 你可以在rails中调用to_query来处理url编码等等。所以可能是这样的:

params = {
  :a => "http://google.com",
  :b => 123
}
url = "http://example.com?#{params.to_query}"

I like Brian's answer. 我喜欢Brian的回答。 Here it is in the form of a method, in case anyone else comes across this. 这是一种方法的形式,以防其他任何人遇到这种情况。

  def url_with_attributes_from_hash(url = "", attr_hash = {})
    url == "" or attr_hash == {} ? "#{url.to_s}" : "#{url.to_s}?#{attr_hash.to_query}"
  end

Writing your own helper for this would be one simple line of code: 为此编写自己的帮助程序将是一行简单的代码:

def twitter_url_for(url, text)
  link_to "Share this url", "http://twitter.com/share?url=#{url}&text=#{text}"
end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM