4

I use Carrierwave to allow users to attach images to their posts. In the list of posts I display the thumbnails (in haml) as follows:

%td= image_tag post.image.url :thumb

If validation fails when creating a new post I display the cache like this:

= image_tag "/#{ImageUploader::cache_dir}/#{post.image_cache}"

What I can't figure out is how to display the cached thumbnail. Checking the filesystem confirms that it lives in the same directory as the cached image. I tried

= image_tag post.image_cache :thumb

but it errors with wrong number of arguments (1 for 0)

4

2 回答 2

5

Okay, finally figured it out.

  1. Carrierwave does cache uploads even in cases of validation error. That's what the cache is for, after all. It relieves the user of the need to reupload the file.

  2. Users of the gem (me, the programmer), don't need to worry about how to access the cache. Just include the cache field in the form and attr_accessible and access the image (or whatever file) like normal. Carrierwave will do the rest transparently. So in my case

    %td= image_tag post.image.url :thumb
    

will display the image correctly, either from the store directory or the cache.

Carrierwave on GitHub

于 2013-08-27T13:35:11.480 回答
1

validation不,因为如果出现错误,AFAIK Carrierwave 不会缓存版本

如果我正确,Carrierwave 会缓存版本并在after回调挂钩中处理它,然后

验证检查在before回调挂钩中执行。

你可以这样

 before_callback :check_for_validation
  // do some logic
 after_callback :cache_the_version and process it 

前面回调中的任何错误都会导致 Carrierwave 绕过后面的回调链

因此,您没有在遇到验证错误时缓存版本。(我认为这是预期的行为,因为如果它们无效,为什么要处理和创建版本)

错误

wrong number of arguments (1 for 0)

这也是预期的行为,因为#{column}_cache在您的情况下 itimage_cache方法不接受任何参数

我认为没有任何方法可以显示版本的缓存图像(在您的情况下thumb),考虑到版本在收到验证错误时永远不会被缓存

如我错了请纠正我 :)

希望这有帮助

于 2013-08-05T14:53:13.107 回答