Search code examples
ruby-on-railsrubyruby-on-rails-3paperclipdragonfly-gem

Assigning Image from URL with Dragonfly


I'm using Dragonfly for handling images on a Rails 3.1 app. I'm struggling with assigning images to a model via the url.

I have this working fine in a form:

<%= form_for [@word, @game, @picture], :html => {:multipart => true} do |f| %> 
  <%= f.hidden_field :retained_image %>
  <p>
    <%= f.label :image, "upload pic" %><br />
    <%= f.file_field :image %>
  </p>
  <p>
    <%= f.label :image_url, "or pic URL" %><br />
    <%= f.text_field :image_url %>
  </p>
  <p>
    <% if @picture.image_uid? %>
    <label>Remove Picture?</label>
    <%= f.check_box :remove_image %>
    <% end %>
  </p>
  <p><%= f.submit %></p>
<% end %>

Dragonfly's documentation states:

Dragonfly provides an accessor for assigning directly from a url:

@album.cover_image_url = 'http://some.url/file.jpg'

But yet when I try in my console:

 => #<Picture id: nil, game_id: nil, user_id: nil, created_at: nil, updated_at: nil, image_uid: nil> 
ruby-1.9.2-p290 > picture.image_url = "http://i.imgur.com/QQiMz.jpg"
 => "http://i.imgur.com/QQiMz.jpg" 
ruby-1.9.2-p290 > picture
 => #<Picture id: nil, game_id: nil, user_id: nil, created_at: nil, updated_at: nil, image_uid: nil> 

It seems to be returning the string of the URL I'm trying to give to Dragonfly, not opening and pulling the image like in the form.

Is there something I'm missing when trying to assign an image based off a url? It seems like it should be pretty straight forward but I can't seem to get anything to work in the ruby console.


Solution

  • are you sure it's not working? What happens when you type (after assigning from a url)

    picture.image
    

    or

    picture.image.size
    

    for example?

    It won't set an image_uid until it's saved, but you have picture.image available to play with.

    The actual fetching from the url happens lazily, i.e. only when needed. Calling 'size' above triggers it, for example.