Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
852 views
in Technique[技术] by (71.8m points)

ruby on rails - How do I defined a variable link_to to an external 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

instead of http://www.example.com

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 %>

and my _micropost.html.erb like this:

<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>

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

Does anyone can help me (I'm a RoR beginner)?

KR, Fabian

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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}"

or maybe add a full_url method to that model that adds it if it's missing.

By the way, you can't use @micropost in that partial because it doesn't exist (you only have @microposts or micropost).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...