所以我的 Rails 4 应用程序中有几个不同的模型可以上传图像。我没有向每个模型添加相同的代码,而是创建了一个可以包含在所有模型中的模块。
这里是:
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 模型(使用这个 mixin):
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
我对这意味着什么或为什么会这样一无所知。任何人都有任何见解?
谢谢!
最佳答案
事实证明,我正在尝试做我在各种模块示例中看到的事情。让它工作很简单:
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
关于ruby-on-rails - 带有 ActiveSupport 的 Rails 4 ActiveRecord 模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17914989/