總的來說這是一個壞主意,用繩子concatenation- 特別打造的網址當你需要做一些像在另一個URL的查詢參數中的URL。
要創建正確編碼的查詢參數,請使用Rails方便的Hash#to_query
方法。
讓我們從裏到外。
# Build the article URL
article_base_url = 'http://example.com/path'
article_url_hash = article.title.parameterize # => "my-article"
article_url = "#{article_base_url}##{article_url_hash}"
# => "http://example.com/path#my-article"
# Next, build the query string for the tweet URL
tweet_url_query = {
status: "Check out #{article.title} #{article_url}"
}.to_query
# => "status=Check%20out%20My%20Article%20http%3A%2F%2Fexample.com%2Fpath%23my-article"
# Finally, build the tweet URL:
base_tweet_url = 'https://twitter.com/home'
tweet_url = "#{base_tweet_url}?#{tweet_url_query}"
# => "https://twitter.com/home?status=Check%20out%20My%20Article%20http%3A%2F%2Fexample.com%2Fpath%23my-article"
<%= link_to tweet_url do %>
<span class="fa fa-twitter-square fa-2x"></span>
<% end %>
正如也許你已經猜到了,它可能是最好把所有這一切在一個幫手:
<%= link_to tweet_url(article.title) do %>
<span class="fa fa-twitter-square fa-2x"></span>
<% end %>
(你可以,當然,將上述內容減少到單個雙行幫手,但代價是可讀性和可測試性,但這將是一個錯誤。)
可能的重複[如何轉義#{從字符串插值](http://stackoverflow.com/questions/1310701/how-do-i-escape-from-string-interpolation) –
@cantido我看到答案和它有點不同。我基本上想在'#{article.title}之前添加一個額外的'#',但似乎並不需要。思考? – gitastic
我明白你的意思了。我試過'「\ ## {article.title}」'這在我的IRB中有效,它對你有用嗎? –