ruby-on-rails-3 – 单个型号上的多个Carrierwave mount_uploader

我有一个名为Recipe的模型,它有两个使用载波的图像,所以在这个模型中我有这个设置载波

mount_uploader :author_photo, AuthorUploader
mount_uploader :photo, PhotoUploader

我还为我的图像添加了多个版本,如拇指,小,中,大

问题是.说我有2张图片

Chocolate_Cake.jpg as the photo
My_Photo.jpg as author_photo

当我进入控制台并加载我的食谱和recipe.to_json时,我从载波中获取了我的图像,但是他们都显示了食谱的照片,而不是作者照片.

     "recipe": [
    {
        "author_photo": {
            "url": "/uploads/recipe/photo/8/Chocolate_Cake.jpg",
            "thumb": {
                "url": "/uploads/recipe/photo/8/thumb_Chocolate_Cake.jpg"
            },
            "small": {
                "url": "/uploads/recipe/photo/8/small_Chocolate_Cake.jpg"
            },
            "medium": {
                "url": "/uploads/recipe/photo/8/medium_Chocolate_Cake.jpg"
            },
            "large": {
                "url": "/uploads/recipe/photo/8/large_Chocolate_Cake.jpg"
            }
        },
        "id": 8,
        "photo": {
            "url": "/uploads/recipe/photo/8/Chocolate_Cake.jpg",
            "thumb": {
                "url": "/uploads/recipe/photo/8/thumb_Chocolate_Cake.jpg"
            },
            "small": {
                "url": "/uploads/recipe/photo/8/small_Chocolate_Cake.jpg"
            },
            "medium": {
                "url": "/uploads/recipe/photo/8/medium_Chocolate_Cake.jpg"
            },
            "large": {
                "url": "/uploads/recipe/photo/8/large_Chocolate_Cake.jpg"
            }
        },

所以出于某种原因,我的json响应并没有正确显示我的上传者.

如果我要在控制台中输入

 recipe.photo
 recipe.author_photo

他们提出了不同的图像网址

最佳答案
经过一些研究和朋友的帮助,我发现我可以覆盖配方模型的as_json方法来修复我得到的响应.

   def as_json(options = {})
     super.merge('photo' => photo.as_json[:photo], 'author_photo' => author_photo.as_json[:author_photo])
   end

该解决方案有效.

转载注明原文:ruby-on-rails-3 – 单个型号上的多个Carrierwave mount_uploader - 代码日志