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