Friday, November 10, 2017

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

Leave a Comment

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)?

1 Answers

Answers 1

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 
If You Enjoyed This, Take 5 Seconds To Share It

0 comments:

Post a Comment