我尝试在rails 3.2应用程序中为某些图像上传设置carrierwave_direct,但似乎无法使用direct_upload_form_for标记呈现表单。
我收到错误“未定义的方法`direct_fog_url'用于#< PostmarkerImage:0x007fdbe07b39f0>”加载包含表单的页面时。
PostmarkerImage是我安装上传器的模型:
class PostmarkerImage < ActiveRecord::Base
attr_accessible :image, :image_cache
belongs_to :postmarker
validates :image, :presence => true
mount_uploader :image, PostmarkerImageUploader
end
image列是一个字符串,我还确保已运行迁移以创建列。上传者现在看起来像这样:
class PostmarkerImageUploader < CarrierWave::Uploader::Base
include CarrierWaveDirect::Uploader
# 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
include CarrierWave::MimeTypes
process :set_content_type
# 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
# 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
# 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
我还确保已经安装了carrierwave_direct,fog,mini_magick和Imagemagick。我可以知道我还错过了什么吗?看起来上传器的安装似乎没有做好。
答案 0 :(得分:5)
管理解决问题:)以防万一有人遇到此问题:
我正在实现一个单独的模型来保存我的图像,而不是将列添加到现有表中。因此,direct_upload_form_for需要列(例如Image.new.image)而不是我返回的对象(例如Image.new)。我想我被form_for部分抛弃,通常需要一个对象!
答案 1 :(得分:1)
对于遇到此错误的任何其他人,您可能无法将正确的对象传递给direct_upload_form_for。假设我们有一个带有头像列的用户模型。它应该看起来像。
型号:
class User < ActiveRecord::Base
mount_uploader :avatar, AvatarUploader
end
控制器:
def edit # Could be any action, but I always direct upload to existing objects
@uploader = @user.avatar
@uploader.success_action_redirect = edit_registration_url(resource)
end
查看(错误):
<%= direct_upload_form_for @uploader do |f| %>
<%= f.file_field :image %>
<% end %>
注意@uploader对象实际上是列 @ user.avatar,而不是对象 @user。这就是OP在他的回答中所说的话。在他的情况下,这更令人困惑,因为对象不是用户,它是PostmarkerImage,我假设它是一个仅存在以保存图像的模型。当您希望一个对象(即邮戳)拥有多个图像时,这种情况很常见。因此,您只为图像创建模型,并在它们之间建立has_many
关系。
陷阱:我在制作中也遇到了很多错误,因为我忘记将控制器中的代码从edit
操作复制到update
操作。如果由于验证而导致上传失败(如文件类型),则需要记住再次设置@uploader!同样,如果您在new
中有上传者,请记得在create
中分配@uploader。