【问题标题】:Rails paperclip static files with absolute url带有绝对 URL 的 Rails 回形针静态文件
【发布时间】:2013-03-19 11:30:14
【问题描述】:

我有一个带有回形针附件的模型:图片

型号:

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

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 paperclip


    【解决方案1】:

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

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

    这将是一个URI 对象,可以将其转换为String 及其.to_s

    【讨论】:

      【解决方案2】:

      根据相同的github issue,使用ActionController::Base.asset_host 更干净,因此会产生助手:

        def add_host_prefix(url)
          URI.join(ActionController::Base.asset_host, url)
        end
      

      这假设您在每个 /config/environments/&lt;environment&gt;.rb 文件中都有以下内容:

      Appname::Application.configure do
      
        # ....
      
        config.action_controller.asset_host = 'http://localhost:3000' # Locally
      
        # ....
      
      end
      

      【讨论】:

        猜你喜欢
        • 2012-09-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-03-21
        • 2017-09-25
        • 1970-01-01
        相关资源
        最近更新 更多