我有两个 Mongoid 模型,Store 和 Product。他们的关系是一个 Store has_many Products,Products belongs_to Store。这些模型中的每一个都有一些可以使用 Carrierwave 附加的图像,看起来像这样:
mount_uploader :logo, ImageUploader
我能够添加和编辑商店模型中的图像。但是在产品中,我只能在创建产品时添加图像,而不能在编辑产品时添加图像。这似乎是一个 deep_copy 问题,类似于在 Mongoid 中如果你有一个名为 urls 的数组并且你想更新该数组,你必须调用
urls_will_change!
所以我尝试在 before_update 回调中调用等效方法 (logo_will_change!),但它什么也没做。我应该在其他什么地方执行此操作还是另一个问题?
最佳答案
下面的代码对我有用,所以可能还有其他问题:
# store model
class Store
include Mongoid::Document
mount_uploader :image, ImageUploader
has_many :products
field :name, type: String
end
# product model
class Product
include Mongoid::Document
mount_uploader :image, ImageUploader
belongs_to :store
field :name, type: String
end
# image uploader
class ImageUploader < CarrierWave::Uploader::Base
storage :file
def store_dir
"uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
end
end
# some test data
@store = Store.new({:name => "store"})
@product = Product.new({:name => "product"})
@store.save
@store.products << @product
# later get the product and update the image
@product = Product.first
puts @product.image.url # blank
@product.update_attributes({:image => File.open("/path/to/image.png")})
puts @product.image.url # now has image url
关于ruby-on-rails - 为什么我不能在 Carrierwave 中编辑此图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7759824/