1

I'm trying to achieve this url on my users profile in a cleaner way: Profile Address: localhost:3000/username

This is how I do it: <%= link_to "localhost:3000#{root_path}#{@user.username}", @user.username %>

Quite an ugly way to do it. I could store the url I want in a variable in a helper or controller or something e.g. shortened_root_url = localhost:3000/ (or site name) and there are other ways I could do it ...

But isn't there a way I could just use root_url and have some magic remove the http:// from the url when displaying on users profile?

NOTE: I'm talking about the URL displayed to the user on his/her page, not in the href attr of an anchor tag.

4sha
  • 326
  • 1
  • 3
  • 12
LondonGuy
  • 10,778
  • 11
  • 79
  • 151

1 Answers1

2

What you're doing is unusual, really... so there probably isn't a direct way of doing it.

you can look into the "url_for" options to see what would be most applicable. http://apidock.com/rails/ActionView/Helpers/UrlHelper/url_for

It has options like "protocol" or "path_only" that might help you build what you need.

For your needs, if all you're doing is removing the protocol, why not just create the full url and use gsub eg:

link_to @user.username, username_url(:username => @user.username).gsub("http://", '')

You'd also need an appropriate route. I've just guessed at your routing here, but say in Rails 2.3.X you'd have something like:

map.username '/:username', :controller => :users, :action => :show
Taryn East
  • 27,486
  • 9
  • 86
  • 108
  • I guess the easier way I can do it right now then is to store the root url address "mysite.com" in a variable and just call that instead. – LondonGuy Nov 03 '11 at 11:47
  • I don't think that's necessary. You can create the whole url using the url_for method (or creating a proper, named url) then just remove the http bit using string-logic (ie gsub). I've added that to my answer. – Taryn East Nov 03 '11 at 11:53
  • Profile Address: <%= link_to root_url(:user => @user.username).gsub("http://", ''), @user.username %> that is close to what I want. URL shows on page without http:// but the url is not shown the way I want it.It shows localhost:3000/?user=username instead of localhost:3000/username – LondonGuy Nov 03 '11 at 12:11
  • That just means you need to set up a proper route for this url. have added an eg to the answer. – Taryn East Nov 03 '11 at 17:54
  • You just want to display the path generated from the route on the page, but leave off the "http://". You don't need `link_to`, just insert the modified path into your page: `<%= username_url(@user).gsub('http://','') %>` – Jonathan Julian Nov 03 '11 at 20:32
  • That's what i said... but there was confusion about how it worked, so I decided to put route in to be explicit :) – Taryn East Nov 04 '11 at 21:30