ipegasus
ipegasus

Reputation: 15242

Ruby On Rails - Image Tag Issue

I would like to know how to specify the full URL src attibute in image_tag?

Currently I use:

image_tag(object.team.team_logo, :alt => object.team.name)

And the src attibute is transformed incorrectly into:

http://0.0.0.0:3000/assets/%20http://a.espncdn.com/i/teamlogos/soccer/500/103.png

I tried runing rake assets:precompile && rake assets:clean_expired but the app still treats the full url as a precompiled asset.

Thanks in advance!

Upvotes: 0

Views: 118

Answers (1)

mu is too short
mu is too short

Reputation: 434585

You need to properly clean and validate your team_logo values before putting them in the database: the first character of your object.team.team_logo value is a space.

If you trace through the image_tag implementation, you'll find that it eventually calls asset_path:

def asset_path(source, options = {})
  source = source.to_s
  return "" unless source.present?
  return source if source =~ URI_REGEXP
  #...

You have a leading space in team_logo so the URI_REGEXP test fails and Rails will prepend the asset path (and URL encode the string, hence the %20 representation of your space).

You should do a few things:

  1. Add a validation to your model to ensure that team_logo is always a well formed URL.
  2. Add a before_validation callback to your model to clean up any stray whitespace in incoming team_logo values.
  3. Go through all the team_logo values in your database and clean them up, you'll probably need to repair or delete some of them by hand.

Once you've cleaned up your data, your image_tag will work as expected.

I suppose you could strip off the whitespace in your view that's pretty nasty and should not be done unless you need an immediate fix to keep the business from failing in the next five minutes. And even then, you'd want to clean up the data and backout the "clean up whitespace in the view" kludge right away.

Upvotes: 2

Related Questions