2011-10-13 39 views
2

我有兩個Mongoid模型,商店和產品。他們的關係是商店has_many產品,以及產品belongs_to商店。每個模型都有可以使用Carrierwave被附加了一些圖片,看起來像這樣:爲什麼我無法在Carrierwave中編輯此圖像?

mount_uploader :logo, ImageUploader 

我能夠添加和編輯是在商店模式的圖像。但是在產品中,我只能在創建產品時添加圖像,而不能編輯產品。這似乎在某種程度上是一個DEEP_COPY問題,類似於如何在Mongoid,如果你有一個數組稱爲URL和要更新該數組,你必須調用

urls_will_change! 

所以我試圖調用等效方法(logo_will_change! )在before_update回調中,但它什麼都不做。還有其他地方我應該這樣做還是另一個問題?

+0

你什麼時候試着上傳一張圖片上的錯誤,或者新的圖像就是不告訴你得到一個錯誤?你可以發佈你的'更新'行動嗎? –

回答

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 
相關問題