ruby-on-rails-3 – Carrierwave:设置图像路径并跳过上传
发布时间:2020-12-17 03:23:13 所属栏目:百科 来源:网络整理
导读:我想设置一些图像而不上传. (它们已经存在,或者其他任务可以保存它们……) 如果我尝试(在rails控制台中): user = User.lastuser.picture = '/some/picture.jpg'user.saveuser.picture # nil 唯一的方法是设置remote_picture_url,然后删除上传(这是愚蠢的)
我想设置一些图像而不上传. (它们已经存在,或者其他任务可以保存它们……)
如果我尝试(在rails控制台中): user = User.last user.picture = '/some/picture.jpg' user.save user.picture # nil 唯一的方法是设置remote_picture_url,然后删除上传(这是愚蠢的) 在carrierwave中是否有任何方法只允许您修改文件名? 解决方法class User < ActiveRecord::Base attr_accessible :picture # Don't want to write to the database,but want to be able to check attr_writer :skip # set a default value def skip @skip ||= false end mount_uploader :image,PictureUploader # Make sure that the skip callback comes after the mount_uploader skip_callback :save,:before,:store_picture!,if: :skip_saving? # Other callbacks which might be triggered depending on the usecase #skip_callback :save,:write_picture_identifier,id: :skip_saving? def skip_saving? skip end end class PictureUploader < Carrierwave::Uploader::Base # You could also implement filename= def set_filename(name) @filename = name end end 假设您在控制台中具有上述设置: user = User.last user.picture.set_filename('/some/picture.jpg') user.skip = true # Save will now skip the callback store_picture! user.save user.picture # /some/picture.jpg 应该注意的是,如果您在控制台中并且更新了具有附加文件的现有记录(即user.picture.file),它将显示旧的URL /位置.如果您退出控制台(假设您不在沙箱模式下)并返回并查询同一对象,则它将具有更新的URL /位置. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |