【问题标题】:Why can't I edit this image in Carrierwave?为什么我不能在 Carrierwave 中编辑此图像?
【发布时间】:2011-10-13 20:07:22
【问题描述】:

我有两个 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!),但它什么也没做。还有其他地方我应该这样做还是另一个问题?

【问题讨论】:

  • 您在尝试上传图片时是否遇到错误,或者新图片不显示?您可以发布您的update 操作吗?

标签: ruby-on-rails ruby mongodb mongoid carrierwave


【解决方案1】:

下面的代码对我有用,所以可能还有其他事情发生:

# 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

【讨论】:

    猜你喜欢
    • 2014-06-06
    • 1970-01-01
    • 1970-01-01
    • 2021-09-21
    • 2014-03-12
    • 2010-09-30
    • 1970-01-01
    • 1970-01-01
    • 2015-09-01
    相关资源
    最近更新 更多