Search code examples
ruby-on-railsimageruby-on-rails-4carrierwavedragonfly-gem

Dragonfly images in a polymorphic association syntax?


I have a pictures model:

class Picture < ActiveRecord::Base
  belongs_to :imageable, polymorphic: true
  dragonfly_accessor :image
end

And then I have two different models that should be able to have pictures:

class Teacher < User 
  has_many :pictures, as: :imageable  
end

class Student < User 
  has_many :pictures, as: :imageable
end

I followed instruction here to setup dragonfly and had it working when I just had one model with an image attribute but now that I want to make its own picture model that other models can have_many of then it stops working: http://markevans.github.io/dragonfly/rails/

In my rails console I can do something like:

teacher = Teacher.last
teacher.pictures 

and get returned an empty active record proxy:

#<ActiveRecord::Associations::CollectionProxy []>

but I cannot do:

teacher = Teacher.last
teacher.image
teacher.picture.image
teacher.pictures.image

When I try to display on my show view:

<%= image_tag @teacher.pictures.thumb('400x200#').url if @teacher.pictures_stored? %>

I get

undefined method `pictures_stored?'

Even if I delete the if @scientist.pictures_stored? I then get this error: undefined method thumb'

I have tried different combinations since dragonfly gives us the dragonfly_accessor :image on our pictures model. But not sure how to actually reference it. Any help is appreciated.


Solution

  • You are trying to call an attribute from a list of pictures.

    You will need to go through each or call the first picture:

    <% teacher.pictures.each do |pic| %>
        <%= image_tag pic.image %>
    <% end %>
    

    or...

    image_tag( teacher.pictures.first.image ) if teacher.pictures.any?

    Hope this helps

    EDIT (In response to your comment below)

    In your Teacher model you could define a method that returns the first picture:

    def first_picture_image
        self.pictures.first.try(:image)
    end
    

    If the teacher has no pictures associated to it, the above method will return nil.