Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I set a default url for images[0] in Carrierwave?

I have a standard image uploader using Carrierwave. I am also using Postgres. So this is what my migration looks like for adding images as JSON:

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

I want to make images[0] always have some image, but it seems like the Carrierwave documentation only covers this for single file uploads. Right now, here is my default_url method:

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

This was working when I only had :image, but now it isn't. Is there any way to set a default for images[0] so that I get a valid images[0].url for every listing I have (despite whether or not a user adds an image to the listing)?

like image 680
Jack Moody Avatar asked Oct 07 '17 18:10

Jack Moody


1 Answers

As Carrierwave is not helping in this matter maybe you can use something like writing a helper or a callback for this job. Here are some suggestions that you may like.

  1. Write a helper
module CarrierwaveHelper
  def render_image_url(images, index)
    return "Default.jpg" if index == 0
    images[index].url
  end
end

and simply call render_image_url(images,0) in your view instead of images[0].url

  1. write a callback in your model

before_create :assign_default_image or maybe you'll need before_update

def assign_default_image
  self.image[0] = "default.jpg"
end
like image 122
Sikandar Tariq Avatar answered Nov 15 '22 19:11

Sikandar Tariq