Using the Rails Environment URL in a MODEL with paperclip

流过昼夜 提交于 2020-01-04 05:19:48

问题


in my users model I have a paperclip setup like this:

  has_attached_file :profile_pic, 
                    :styles => {:large => "300x300>", :medium => "150x150>", :small => "50x50#", :thumb => "30x30#" },
                    :default_style => :thumb,
                    :default_url => '/images/:attachment/default_:style.png',

How do I make the default URL, include the full URL?

http://0.0.0.0:3000/images/:attachment/default_:style.png 
or http://sitename.com/images/:attachment/default_:style.png

回答1:


In Rails 3 add: include Rails.application.routes.url_helpers in your model.

In Rails 2 add: include ActionController::UrlWriter in your model.

Then root_url contains the base url of your app. So then you can do:

has_attached_file :profile_pic, 
                    :styles => {:large => "300x300>", :medium => "150x150>", :small => "50x50#", :thumb => "30x30#" },
                    :default_style => :thumb,
                    :default_url => "#{root_url}/images/:attachment/default_:style.png",



回答2:


root_url wont work straightaway.

you need to assign Rails.application.routes.default_url_options[:host] before using #{root_url}.

so you could set the config into your envs. for staging.rb/production.rb/development.rb

  config.after_initialize do
    Rails.application.routes.default_url_options[:host] = 'http://localhost:3000'
  end



回答3:


Simplest alternative method:

include in you're class

include Rails.application.routes.url_helpers

my Model as Example to get paperclip images absolute url:

class Post < ActiveRecord::Base
  include Rails.application.routes.url_helpers

    validates :image, presence: true

      has_attached_file :image, styles: { :medium => "640x", thumb: "100x100#" } # # means crop the image
        validates_attachment_content_type :image, :content_type => /\Aimage\/.*\Z/

  def image_url
   relative_path =  image.url(:medium)
   self.add_host_prefix relative_path
  end

 def thumb_url
   relative_path = image.url(:thumb)
   self.add_host_prefix relative_path
 end

  def add_host_prefix(url)
    URI.join(root_url, url).to_s
  end
end

and in controller:

class Api::ImagesController < ApplicationController

  def index
    @posts =  Post.all.order(id: :desc)
    paginated_records = @posts.paginate(:page => params[:page], :per_page => params[:per_page])
    @posts = with_pagination_info( paginated_records )
    render :json => @posts.to_json({:methods => [:image_url, :thumb_url]})
  end
end

finally: add

Rails.application.routes.default_url_options[:host] = 'localhost:3000'

in:

Your_project_root_deir/config/environments/development.rb

although helpers can be accessible only in views but this is working solution.



来源:https://stackoverflow.com/questions/4231335/using-the-rails-environment-url-in-a-model-with-paperclip

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!