我有一个带有一个回形针附件的模型:图像
模型:
class HomeScreen < ActiveRecord::Base
before_create { !HomeScreen.has_record? }
validates :image, :attachment_presence => true
attr_accessible :image
has_attached_file :image
def self.has_record?
if HomeScreen.last
true
else
false
end
end
end
我的控制器的显示方法应该用相对路径返回图像,而json应该用域返回绝对url,我怎么能这样做呢?
控制器:
class HomeScreenController < ApplicationController
# GET /home_screen
def show
@home_screen = HomeScreen.last
respond_to do |format|
format.html
format.json { render json: @home_screen }
end
end
发布于 2013-03-19 11:41:02
根据github问题,您可以执行以下操作:
image_uri = URI.join(request.url, @home_screen.image.url)
这将是一个URI
对象,可以将其转换为带有.to_s
的String
发布于 2014-01-09 18:09:50
根据同一个github问题,使用ActionController::Base.asset_host
更干净,这样就可以得到帮助者:
def add_host_prefix(url)
URI.join(ActionController::Base.asset_host, url)
end
这假设您在每个/config/environments/<environment>.rb
文件中都有以下内容:
Appname::Application.configure do
# ....
config.action_controller.asset_host = 'http://localhost:3000' # Locally
# ....
end
https://stackoverflow.com/questions/15498269
复制相似问题