WebQube
WebQube

Reputation: 8961

rails carrierwave optional url to image results in an error on rails 3

I am trying to set up an upload image page where the user can optionaly upload an image url instead. I am using carrierwave The view:

<%= form_for @rating, :html => {:multipart => true} do |f| %>

    <p>
      <%= f.file_field :pic_url %>
    </p>

    <p>
      <%= f.label :remote_pic_url_url, 'or image url' %>
      <br/>
      <%= f.text_field :remote_pic_url_url %>
    </p>

    <div class="actions">
      <%= f.submit 'Upload Picture', :class => 'btn btn-primary' %>
    </div>

the model:

class Rating < ActiveRecord::Base
  attr_accessible :pic_url, :remote_pic_url_url, :rating

  mount_uploader :pic_url , ImageUploader
end

when I try to input just the image url, I get a error msg: Pic url You are not allowed to upload "" files, allowed types: jpg, jpeg, gif, png

How do I make that field optional. I was under the impression that remote_{columnName}_url is the convention for adding additional url field in carrierwave, and that will take care of that for me..

controller code:

# POST /ratings
  # POST /ratings.json
  def create
    @rating = Rating.new(params[:rating])

    respond_to do |format|
      if @rating.save
        format.html { redirect_to @rating, :notice => 'Rating was successfully created.' }
        format.json { render :json => @rating, :status => :created, :location => @rating }
      else
        format.html { render :action => "new" }
        format.json { render :json => @rating.errors, :status => :unprocessable_entity }
      end
    end
  end

Upvotes: 0

Views: 1411

Answers (1)

Chris Salzberg
Chris Salzberg

Reputation: 27374

See this thread.

The error you're getting (You are not allowed to upload "" files, allowed types: jpg, jpeg, gif, png) is the same one you get with the following:

@rating.remote_pic_url_url = "http://www.google.com"
@rating.save

The problem here is that Carrierwave opens the URL, then calls the resulting file with base_uri.path, which returns /, hence the error. If you were entering a URL which has no extension, then this is the cause.

If not, then I'm not sure why it's not working. I use the same approach in my own project (i.e. setting remote_{columnname}_url and then saving the record) and it works fine. Although I don't normally use the extension whitelist validator, I added one and (in the console at least) it works fine as well with valid URLs (i.e. URLs pointing to images with valid extensions).

Can you try the steps below in the console and see if it saves properly? (insert some valid URL to a JPG/GIF/PNG file):

@rating = Rating.new(remote_pic_url_url: 'http://...')
@rating.save

Upvotes: 1

Related Questions