How can I access the current host and model port in Rails?

I ran into the following problem:

I am doing a Rails 4 webapp and we use paperclip for profile images. If the user does not upload the image, we provide it by default (for example, facebook font placeholder). Since paperclip simplifies the default image processing, we do the following in the model Profile:

class Profile < ActiveRecord::Base
  belongs_to :user
  has_attached_file :image, :styles => { :medium => "300x300", :thumb => "100x100" }, :default_url => "assets/profiles/:style/placeholder.gif"
end

The big problem is that I need the full image URL, not just the path, so I'm trying to get the host and port to this path. Using action view helpers didn't help ( asset_urlhelper)

I was thinking of initializing some kind of constant or configuration or environment variable for the environment. Will it be right? Any other suggestions?

EDIT: I forgot to mention this: a resource (profile) can have its own image or by default. When it has a custom image, we save it in Amazon S3, in which case it profile.image.urlreturns the full URL. In another case, when it does not have a custom image, it has a default image saved in app/assets/images, in which case it profile.image.urlreturns only the path. I would like the method to image.urlconsistently return the full URLs. - flyer88 is currently editing

+4
source share
1 answer

, , API, , , .. . - :

# routes.rb
get "/profile/:id" => "api#profile"

# profile.rb
def image_url_or_default request
  if image
    "#{request.protocol}#{request.host_with_port}#{image.url}"
  else
    "http://s3.amazon.com/my_bucket/default.jpg"
  end
end

# api_controller.rb
def profile
  profile = Profile.find params[:id]
  render text:profile.image_url_or_default(request)
end

profile.image.url URL- .

+3

All Articles