对于那些熟悉 rubygems 的人,我使用 CarrierWave 允许在我的应用程序上上传照片。
这是我在视图中使用的代码
Add a photo:
<%= f.file_field :image %>
How can I make a checkbox appear in my View along with some text above it only IF a photo is selected for upload?
这是完整的 post.html.erb 视图
<%= form_for @post, :html => {:multipart => true} do |f| %>
<%= render 'shared/error_messages', object: @post %>
<div class="field">
<%= f.text_area :content, :cols => 5, :rows => 5 %>
</div>
Add a photo:<br>
<%= f.file_field :image %>
<br>
<%= f.submit "Submit", class: "btn btn-large btn-primary" %>
<% end %>
这是post模型(相关部分)
class Post < ActiveRecord::Base
attr_accessible :content, :image
belongs_to :user
mount_uploader :image, ImageUploader
end
和上传者模型
class ImageUploader < CarrierWave::Uploader::Base
include CarrierWave::MiniMagick
# Choose what kind of storage to use for this uploader:
storage :file
# storage :fog
# 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}"
end
# Provide a default URL as a default if there hasn't been a file uploaded:
# def default_url
# # For Rails 3.1+ asset pipeline compatibility:
# # asset_path("fallback/" + [version_name, "default.png"].compact.join('_'))
#
# "/images/fallback/" + [version_name, "default.png"].compact.join('_')
# end
# Avoid using model.id or version_name here, see uploader/store.rb for details.
def filename
"#{secure_token(10)}.#{file.extension}" if original_filename.present?
end
def cache_dir
"#{Rails.root}/tmp/uploads"
end
protected
def secure_token(length=16)
var = :"@#{mounted_as}_secure_token"
model.instance_variable_get(var) or model.instance_variable_set(var, SecureRandom.hex(length/2))
end
end