[英]How can I access current host and port on a model in Rails?
I am facing the following problem: 我面临以下问题:
I am doing a Rails 4 webapp and we are using paperclip for profile images. 我正在做一个Rails 4 webapp,我们正在使用paperclip进行个人资料图片。 If the user does not upload an image we provide a default one (like the facebook silhouette placeholder). 如果用户没有上传图像,我们提供默认图像(如facebook剪影占位符)。 So as paperclip eases handling default images, we are doing the following in the Profile
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 complete URL of the image and NOT only the path so I am struggling to get the host and port before that path. 最大的问题是我需要图像的完整URL而不仅仅是路径,因此我很难在该路径之前获取主机和端口。 Using action view helpers there did not help ( asset_url
helper) 使用动作视图助手没有帮助( asset_url
助手)
I was thinking in initializing some constant or configuration or environment variable per environment. 我在考虑为每个环境初始化一些常量或配置或环境变量。 Will it be correct? 这是对的吗? Any other suggestions? 还有其他建议吗?
EDIT: I forgot to mention this: The resource (Profile) may have a custom picture or a default one. 编辑:我忘了提到这个:资源(配置文件)可能有自定义图片或默认图片。 When it has a custom image, we store it in Amazon S3 and in that case profile.image.url
returns full URL. 当它有自定义图像时,我们将其存储在Amazon S3中,在这种情况下, profile.image.url
将返回完整的URL。 In the other case, when it has not a custom picture it has a default image stored in app/assets/images
and in that case profile.image.url
returns just the path. 在另一种情况下,当它没有自定义图片时,它有一个存储in app/assets/images
的默认图像,在这种情况下, profile.image.url
只返回路径。 I would like that the method image.url
consistently return full URLs. 我希望方法image.url
始终返回完整的URL。 – flyer88 just now edit - flyer88刚刚编辑
If, as you mention in your comment, you are providing an API endpoint, it might make more sense to determine the host, port, etc. in the controller. 如果您在评论中提到的是提供API端点,那么确定控制器中的主机,端口等可能更有意义。 Something like this: 像这样的东西:
# 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 will be the full URL of the image. profile.image.url将是图像的完整URL。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.