ruby-on-rails - 为什么我不能在 Carrierwave 中编辑此图像?

标签 ruby-on-rails ruby mongodb mongoid carrierwave

我有两个 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/

相关文章:

ruby - 用 ruby​​ 删除文件的前两行

ruby-on-rails - 使用 rspec 检查错误的枚举

mongodb - Zend Framework 2 + Doctrine ODM, "The Class was not found in the chain configured namespaces"错误?

arrays - 在 mongodb 数组中查找最接近的值

mysql - 查找在特定时间范围内(任何一天)创建的用户

javascript - 侧边栏和主页持久性 - Rails

ruby-on-rails - Ruby/Rails 报告工具?

ruby-on-rails - 覆盖注册 Controller 时设计 'Unknown action'

ruby-on-rails - 是否可以在 Rails 中使用单个模型管理多个表?

php - 如何将超时设置为无限以避免 php 中的 MongoCursorTimeoutException