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.
- 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
- 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
0 comments:
Post a Comment