ruby-on-rails - 带有 ActiveSupport 的 Rails 4 ActiveRecord 模块

标签 ruby-on-rails ruby activerecord ruby-on-rails-4 activesupport

所以我的 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/

相关文章:

ruby-on-rails - 不理解在 Rails 中使用 Grape API gem 的嵌套资源

Mysql 到 Postgresql Rails PG::GroupingError: 错误:

ruby - 将 StringIO 写入临时文件

ruby-on-rails - 评论作者。 rails

ruby-on-rails - 如何计算数组中具有特定属性值的项目?

ruby-on-rails - Rails 5 Eager load 然后 find_by

sql - “NOT IN”条件不适用于列表中的 'NULL'

ruby-on-rails - 如何为 Rails View 返回一个字符串

ruby-on-rails - 回滚 : what are the benefits of erb in Rails code?

ruby-on-rails - 如何拥有线程安全的 Rails 初始化器?