我想设置一些图片而不上传。 (它们已经存在,或者其他任务可以保存它们......)
如果我尝试(在rails控制台中):
user = User.last
user.picture = '/some/picture.jpg'
user.save
user.picture # nil
唯一的方法是设置remote_picture_url,然后删除上传(这是愚蠢的)
在carrierwave中是否有任何方法只允许您修改文件名?
答案 0 :(得分:6)
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, :before, :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 /位置。