2

I have a model with one paperclip attachment :image

Model:

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

show method of my conttroller should return image with relative path but json should return absolute url with domain, how can I do that?

Controller:

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
4

2 回答 2

5

根据github issue,您可以执行以下操作:

image_uri = URI.join(request.url, @home_screen.image.url)

这将是一个URI对象,可以String用它的.to_s

于 2013-03-19T11:41:02.770 回答
1

根据相同的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
于 2014-01-09T18:09:50.280 回答