2

因此,我有幾個不同的模型在我的Rails 4應用程序中有圖像上傳。我沒有爲每個模型添加相同的代碼,而是創建了一個模塊,我可以將其包含到所有模型中。Rails 4與ActiveSupport ActiveRecord模塊

在這裏:在這種情況下

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 

Medium(單數的介質)是在其上有紙夾的多態模型。 attr_accessor是f.file_field:我在各種表單上的照片。

這裏是我的PurchaseType模型(使用此混入):

class PurchaseType < ActiveRecord::Base 
    include WithImage 

    validates_presence_of :name, :type, :price 
end 

因此,這裏的東西,after_save的偉大工程在這裏。然而,當我去到控制檯,並做PurchaseType.last.photo_url我得到以下錯誤:

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

我一點也不知道線索,這意味着什麼,或者爲什麼它正在發生。任何人有任何見解?

謝謝!

+0

我應該提到我有這個文件在lib/with_image.rb,我正確地包括它。 – goddamnyouryan

+1

我懷疑你的'''WithImage'模塊出現錯誤後,你的'class ActiveRecord :: Base'猴子補丁。你爲什麼需要這個? –

+0

@ muistooshort你就是。我找到了答案,並在下面添加了答案。 – goddamnyouryan

回答

1

事實證明,我試圖做的事情,我看過各種模塊的例子。它很容易得到它的工作:

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