使用回形针在MODEL中使用Rails环境URL
在我的用户模型中,我有一个像这样的回形针设置:
has_attached_file :profile_pic, :styles => {:large => "300x300>", :medium => "150x150>", :small => "50x50#", :thumb => "30x30#" }, :default_style => :thumb, :default_url => '/images/:attachment/default_:style.png',
如何制作默认url,包含完整url?
http://0.0.0.0:3000/images/:attachment/default_:style.png or http://sitename.com/images/:attachment/default_:style.png
在Rails 3中添加:在模型中include Rails.application.routes.url_helpers
。
在Rails 2中添加:在模型中include ActionController::UrlWriter
。
然后root_url
包含您应用的基本url。 那么你可以这样做:
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",
root_url不会直接工作。
在使用#{root_url}之前,您需要分配Rails.application.routes.default_url_options [:host]。
所以你可以将配置设置为envs。 用于staging.rb / production.rb / development.rb
config.after_initialize do Rails.application.routes.default_url_options[:host] = 'http://localhost:3000' end
最简单的替代方法:
包括你在课堂上
include Rails.application.routes.url_helpers
我的模型作为示例获取回形针图像绝对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
并在控制器中:
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
最后:添加
Rails.application.routes.default_url_options[:host] = 'localhost:3000'
在:
Your_project_root_deir/config/environments/development.rb
虽然助手只能在视图中访问,但这是有效的解决方案。