CarrierWave default_url not triggering

2019-09-03 10:57发布

I'm having a hard time getting this to work. Right now I'm using the image_tag helper on my view pages. If there isn't an image loaded, I need it to use the fallback from Carrierwave instead of just throwing an error.

For my setup I'm using fog for storage, I feel like that might be part of the problem.

def default_url
  asset_path("fallback/default.jpg")
end

Does Carrierwave just find any image that isn't set? Or is there some special way I'm supposed to grab the image url for it to work? This is what I have now.

<%= image_tag(property.assets.first!.image_url, :width => "200") %>

Asset.rb

require 'file_size_validator'
class Asset < ActiveRecord::Base
  validates :image_url, uniqueness: true
  validates :image_url, allow_blank: true, format: {
      with: %r{\.(gif|jpg|png)$}i,
      message: 'must be a URL for GIF, JPG or PNG image.'
  },
            :file_size => {
                :maximum => 0.5.megabytes.to_i
            }

  attr_accessible :image_url, :property_id
  belongs_to :property
  mount_uploader :image_url, ImageUploader

end

Property.rb

  validates :street_address, :city, :state, :description, :price, :deposit, :beds, :baths, :presence => true
  validates :street_address, :uniqueness => true
  validates :price, :deposit, numericality: {greater_than_or_equal_to: 0.01}

  has_many :assets, :dependent => :destroy

  attr_accessible :street_address, :street_address2, :city, :state, :zip, :country, :description, :price, :beds, :baths,
                  :deposit, :availability, :leased, :sqft, :pets
  attr_accessible :assets_attributes
  accepts_nested_attributes_for :assets, :reject_if => lambda { |p| p[:image_url].blank? }, :allow_destroy => true

1条回答
虎瘦雄心在
2楼-- · 2019-09-03 11:15

Try <%= image_tag(property.assets.first!.image_url.url, :width => "200") %>

Let's assume you are in rails console and you have an asset with an image. While Asset.first.image_url looks like its returning something like a url (assuming you are using remote storage), but its actually not a string, it's an uploader. Asset.first.image_url.class will return ImageUploader. To get the url, you need to add call the url method of the uploader.

查看更多
登录 后发表回答