Domanda

So I have a few different models in my Rails 4 app that have image uploads. Rather than adding identical code to each of the models I've created a module that I can include into all of them.

Here it is:

module WithImage
  extend ActiveSupport::Concern

  included do
    attr_accessor :photo

    has_one :medium, as: :imageable

    after_save :find_or_create_medium, if: :photo?

    def photo?
      self.photo.present?
    end

    def find_or_create_medium
      medium = Medium.find_or_initialize_by_imageable_id_and_imageable_type(self.id, self.class.to_s)
      medium.attachment = photo
      medium.save
    end
  end

  def photo_url
    medium.attachment if medium.present?
  end
end

class ActiveRecord::Base
  include WithImage
end

A Medium (singular of media) in this case is a polymorphic model that has paperclip on it. The attr_accessor is a f.file_field :photo that I have on the various forms.

Here's my PurchaseType Model (that uses this mixin):

class PurchaseType < ActiveRecord::Base
  include WithImage

  validates_presence_of :name, :type, :price
end

So here's the thing, the after_save works great here. However, when I go to the console and do PurchaseType.last.photo_url I get the following error:

ActiveRecord::ActiveRecordError: ActiveRecord::Base doesn't belong in a hierarchy descending from ActiveRecord

I haven't the faintest clue what this means or why it is happening. Anyone have any insight?

Thanks!

È stato utile?

Soluzione

It turns out I was trying to do things I had seen in various examples of modules. It was simple to get it working:

module WithImage
  extend ActiveSupport::Concern

  included do
    attr_accessor :photo

    has_one :medium, as: :imageable

    after_save :find_or_create_medium, if: :photo?

    def photo?
      self.photo.present?
    end

    def find_or_create_medium
      medium = Medium.find_or_initialize_by_imageable_id_and_imageable_type(self.id, self.class.to_s)
      medium.attachment = photo
      medium.save
    end

    def photo_url
      medium.attachment.url if medium.present?
    end
  end
end
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top