【问题标题】:How do I set a default url for images[0] in Carrierwave?如何在 Carrierwave 中为图像 [0] 设置默认网址?
【发布时间】:2017-10-07 18:33:21
【问题描述】:

我有一个使用 Carrierwave 的标准图片上传器。我也在使用 Postgres。所以这就是我的迁移将图像添加为 JSON 的样子:

class AddImagesToListings < ActiveRecord::Migration[5.1]
  def change
    add_column :listings, :images, :json
    remove_column :listings, :image
  end
end

我想让 images[0] 总是有一些图像,但似乎 Carrierwave 文档仅涵盖单个文件上传的内容。现在,这是我的 default_url 方法:

def default_url(*args)
    ActionController::Base.helpers.asset_path("default/" + ["default.jpg"].compact.join('_'))
end

这在我只有 :image 时有效,但现在不行了。有没有办法为 images[0] 设置默认值,以便我为我拥有的每个列表获得有效的 images[0].url(不管用户是否将图像添加到列表中)?

【问题讨论】:

    标签: ruby-on-rails json carrierwave


    【解决方案1】:

    由于 Carrierwave 在这件事上没有帮助,也许您可​​以使用诸如为此工作编写帮助程序或回调之类的东西。 以下是您可能喜欢的一些建议。

    1. 写一个助手
    module CarrierwaveHelper
      def render_image_url(images, index)
        return "Default.jpg" if index == 0
        images[index].url
      end
    end
    

    只需在视图中调用 render_image_url(images,0) 而不是 images[0].url

    1. 在模型中编写回调

    before_create :assign_default_image 或者你可能需要 before_update

    def assign_default_image
      self.image[0] = "default.jpg"
    end
    

    【讨论】:

    • 你知道carrierwave是否有内置功能来处理这个问题吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-09-04
    • 1970-01-01
    • 1970-01-01
    • 2018-09-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多