如何将此href转换为Rails友好link_to

时间:2014-09-03 07:40:08

标签: ruby-on-rails ruby-on-rails-4

我想转换一下:

<a class="btn btn-google-plus" href="https://plus.google.com/share?url=SHAREMESSAGE" title="Share on Google+" target="_blank">
     <i class="fa fa-google-plus"></i>
</a>

进入不使用网址中的link_to的Rails友好post.title,并且还包含指向当前帖子的链接。

换句话说,我开始在HTML中这样做:

<a class="btn btn-google-plus" href='https://plus.google.com/share?url=<%= "#{post.title} - Read more at #{post}" %>' title="Share on Google+" target="_blank">
    <i class="fa fa-google-plus"></i>
</a>

这个问题是这会产生这样的URL(Twitter等价,但原理是一样的):

http://twitter.com/home?status=PNPYO%20saddened%20at%20passing%20of%20Roger%20Clarke%20-%20Read%20more%20at%20#<Post:0x00000101660e98>

返回Post个对象的位置。我遇到的问题是,我不太确定如何在link_to内生成link_to。这甚至可能吗?

这就是我希望Twitter上的最终状态:

PNPYO saddened at passing of Roger Clarke - Read More at http://example.com/pnpyo-saddened-at-passing-of-roger-clarke

如何以最友好的Rails方式实现这一目标?如果不能使用link_to帮助程序,我不反对使用常规的href标记。但无论哪种方式,我仍然需要能够在状态消息中生成link_to

2 个答案:

答案 0 :(得分:1)

您可以实现以下目标:

<%= link_to "https://plus.google.com/share?url=#{post.title} - Read more at #{post}", :class => "btn btn-google-plus" :title => "Share on Google+" :target => "_blank" do %>
  <i class="fa fa-google-plus"></i>
<% end %>

答案 1 :(得分:1)

您不想在link_to内拨打link_to,但您想直接拨打 url_helper

rails中的

link_to是一个帮助方法,它为链接生成必要的html代码。无论您是否想要使用此便捷功能,您要搜索的是生成 url 的直接方法,您可以将其连接成一个字符串。

只需使用以下作为锚点的href:

http://twitter.com/home?status=<%=u "#{post.title} - Read more at #{post_url(post)}" %>

(&lt;%= u%&gt;执行字符串的url编码)

相关问题