Rails Carrierwave White_List 不抛出异常
刚开始将 Carrierwave 与 Rails 一起使用,一切进展顺利,除了一个小例外。我创建了一个“ImageUploader”类,如下所示:
class ImageUploader < CarrierWave::Uploader::Base
include CarrierWave::RMagick
def extension_white_list
%w(jpg jpeg gif png)
end
end
和一个控制器操作,如下所示:
def update
@user = current_user
if params[:user].nil? || params[:user][:image].nil?
redirect_to user_path(@user)
else
if @user.update_attribute(:image, params[:user][:image])
flash[:success] = "Profile updated successfully!"
redirect_to user_path(@user)
else
flash[:error] = "Changes could not be saved."
render :action => 'edit'
end
end
end
在这种情况下,我将上传器安装在我的 User.rb 中,如下所示:
mount_uploader :image, ImageUploader
问题是,根据 Carrierwave README,上传的文件扩展名不在extensions_white_list中应该会使记录无效。就我而言,我特意通过上传不在白名单上的各种扩展名的文件来测试该应用程序,并且没有引发任何错误。事实上,@user.update_attribute 似乎通过了,我通常会被重定向到 user_path(@user) 并带有 flash[:success] 消息。图像本身实际上并未更改,但我希望能够捕获错误并在扩展类型不正确的情况下重定向到“编辑”页面。关于我在这里做错了什么有什么想法吗?
Just started using carrierwave with Rails and things have been going smoothly with one minor exception. I created a "ImageUploader" class which looks so:
class ImageUploader < CarrierWave::Uploader::Base
include CarrierWave::RMagick
def extension_white_list
%w(jpg jpeg gif png)
end
end
and a controller action which looks like so:
def update
@user = current_user
if params[:user].nil? || params[:user][:image].nil?
redirect_to user_path(@user)
else
if @user.update_attribute(:image, params[:user][:image])
flash[:success] = "Profile updated successfully!"
redirect_to user_path(@user)
else
flash[:error] = "Changes could not be saved."
render :action => 'edit'
end
end
end
In this case I mounted the uploader in my User.rb like so:
mount_uploader :image, ImageUploader
Problem is, according to the Carrierwave README, uploaded files with extensions not in the extensions_white_list should make the record invalid. In my case I have purposely been testing the app by uploading files with various extensions not on the white list and no error is being raised. In fact, @user.update_attribute seems to pass and I am usually redirected to user_path(@user) with a flash[:success] message. The image itself is not actually changed, but I would like to be able to catch the error and redirect to the 'edit' page in case of an incorrect extension type. Any ideas on what I am doing wrong here?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
对于任何感兴趣的人,我自己都找到了解决方法。这不是最优雅的解决方案,但无论如何,这对我有用:
For anyone interested I sort of found a workaround for this myself. Not the most elegant solution, but in any case here's what worked for me:
仅供参考,CarrierWave 文档声明如下:
FYI the CarrierWave documentation states the following: