如何将变量 link_to 定义为外部 URL [英] How do I defined a variable link_to to an external URL
问题描述
在我的网站上,用户拥有个人资料,其中包含指向其个人外部网站的链接.我以 website 名称存储在 postgresql 数据库中的站点的 url.当我测试结果时,我总是得到这样的网址:
On my site a user has a personal profile with a link to his personal external website. The url of the sites I store in a postgresql database under the name website. When I test the result, I always get a url like this:
http://localhost:3000/www.example.com
而不是 http://www.example.com
我的视图 index.html.erb 如下所示:
My view index.html.erb looks like this:
<% provide(:title, 'All projects') %>
<h1>All projects</h1>
<%= will_paginate %>
<ul class="microposts">
<%= render @microposts %>
</ul>
<%= will_paginate %>
和我的 _micropost.html.erb 像这样:
<li>
<span class="title"><%= micropost.title %></span>
<span class="website"><%= link_to micropost.website, micropost.website %></span>
<span class="content"><%= micropost.content %></span>
<span class="timestamp">
Posted <%= time_ago_in_words(micropost.created_at) %> ago.
</span>
</li>
我不知道在这种情况下有什么问题.如果我在 micropost.website 之前设置 @,它会给我一个错误 undefined method `website' for nil:NilClass
I don't know what's the problem in this case. If I set a @ before micropost.website it gives me an error undefined method `website' for nil:NilClass
有人可以帮助我吗(我是 RoR 初学者)?
Does anyone can help me (I'm a RoR beginner)?
KR,法比安
推荐答案
听起来您存储的 URL 没有 http://
,因此它们被解释为相对 URL.你只需要做这样的事情:
It sounds like you are storing URLs without the http://
so they are being interpreted as relative URLs. You just need to do something like this:
link_to micropost.website, "http://#{micropost.website}"
或者可能向该模型添加一个 full_url
方法,如果它丢失,则添加它.
or maybe add a full_url
method to that model that adds it if it's missing.
顺便说一句,你不能在那个部分使用 @micropost
因为它不存在(你只有 @microposts
或 micropost
代码>).
By the way, you can't use @micropost
in that partial because it doesn't exist (you only have @microposts
or micropost
).
这篇关于如何将变量 link_to 定义为外部 URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!