簡體   English   中英

如何在Rails中訪問模型上的當前主機和端口?

[英]How can I access current host and port on a model in Rails?

我面臨以下問題:

我正在做一個Rails 4 webapp,我們正在使用paperclip進行個人資料圖片。 如果用戶沒有上傳圖像,我們提供默認圖像(如facebook剪影占位符)。 因此,當回形針輕松處理默認圖像時,我們在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

最大的問題是我需要圖像的完整URL而不僅僅是路徑,因此我很難在該路徑之前獲取主機和端口。 使用動作視圖助手沒有幫助( asset_url助手)

我在考慮為每個環境初始化一些常量或配置或環境變量。 這是對的嗎? 還有其他建議嗎?

編輯:我忘了提到這個:資源(配置文件)可能有自定義圖片或默認圖片。 當它有自定義圖像時,我們將其存儲在Amazon S3中,在這種情況下, profile.image.url將返回完整的URL。 在另一種情況下,當它沒有自定義圖片時,它有一個存儲in app/assets/images的默認圖像,在這種情況下, profile.image.url只返回路徑。 我希望方法image.url始終返回完整的URL。 - flyer88剛剛編輯

如果您在評論中提到的是提供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。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM