avatar_uploader.rb
# encoding: utf-8
class AvatarUploader < CarrierWave::Uploader::Base
# Include RMagick or MiniMagick support:
# include CarrierWave::RMagick
include CarrierWave::MiniMagick
# Include the Sprockets helpers for Rails 3.1+ asset pipeline compatibility:
# include Sprockets::Helpers::RailsHelper
# include Sprockets::Helpers::IsolatedHelper
# Choose what kind of storage to use for this uploader:
storage :file
# storage :fog
# Override the directory where uploaded files will be stored.
# This is a sensible default for uploaders that are meant to be mounted:
def store_dir
# "uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
# "uploads/company/#{Time.now.to_i.to_s}"
'public/upload/'
end
# Provide a default URL as a default if there hasn't been a file uploaded:
def default_url
"avatar/#{version_name}.png"
end
# Process files as they are uploaded:
# process :scale => [200, 300]
#
# def scale(width, height)
# # do something
# end
# Create different versions of your uploaded files:
# version :thumb do
# process :scale => [50, 50]
# end
version :normal do
process resize_to_fill: [48, 48]
end
version :large do
process resize_to_fill: [64, 64]
end
# Add a white list of extensions which are allowed to be uploaded.
# For images you might use something like this:
def extension_white_list
%w(jpg jpeg gif png)
end
# Override the filename of the uploaded files:
# Avoid using model.id or version_name here, see uploader/store.rb for details.
# def filename
# "something.jpg" if original_filename
# end
end
new.html.erb
<%= form_for(@company) do |f| %>
<%= render 'shared/company_error_messages'%>
<%= f.file_field :avatar %>
<%= f.hidden_field :avatar_cache %>
<% end %>
show.html.erb
<%= image_tag(@company.avatar_url(:large)) if @company.avatar %>
controller
class CompaniesController < ApplicationController
def index
@companies = Company.paginate(page: params[:page], per_page: 6)
respond_to do |format|
format.html
format.json {render json: {company: @companies}}
end
end
def new
@company = Company.new
end
def show
@company = Company.find(params[:id])
@company_jobs = @company.company_jobs.paginate(page: params[:page])
end
def create
@company = Company.new(company_params)
@company.avatar = params[:file]
@company.avatar = [File.open("public/uploads/")]
if @company.save
redirect_to @company
else
render 'new'
end
end
def update
end
private
def company_params
params.require(:company).permit(:name, :describe, :contact,
:product, :location, :field,
:homepage, :funder,
:address)
end
end
现在每次在 show 页面中显示的都是 default_url 定义的图片,好像 store_dir 并没有起作用。
我的问题是,在 store_dir 方法中,图片的存储路径怎么写,是要自己创建文件夹吗,如果是文件夹要在哪里创建。 菜鸟求教,谢谢